import {getGradeList,getCategoryList,createIntegralProService,getIntegralMallProInfo,createCategoryService} from '@/service/api/mallApi.js';
import cardTemp from '@/components/libs/cardTemp';
import dmUploadAvatar from '@/components/upload/avatar';
import {formateDateTimeByType} from '@/utils/index.js';
export default {
  components:{
    cardTemp,
    dmUploadAvatar
  },
  data() {
    return {
      form:{
        integralMallProId:'',
        proReferId:'',
        proName:'', // String 商品名字，优惠券就是所选券的名字。 (必填)
        giftImg:{ //  (必填)
          imgUrl:'',   // giftImageUrls
          code:'' // giftImageFiledCodes
        },
        proCategoryId:'', // String 礼品的分类  (必填)
        integralCost:100, // Number 100 积分费用 (必填)
        cashCost:1, // Number 现金费用，两位小数
        costValue:1, // Number 礼品成本，两位小数
        memberGradeArr:[],  // array 适用会员 这里是数组 传给后台要拼接为字符串数组逗号隔开
        limitTimes:0,
        exchangeDateType:1,
        exchangeTimeType:1, // 兑换时间类型 1:全部 2:部分时段
        proShowStatus:1,
        changeType:2, // Number 兑换方式1:微信兑换 2:快递发货 3:在线发货
        releaseType:1,

        exchangeFixDate:['',''], // exchangeFixDateBegin // exchangeFixDateEnd,
        exchangeDateDayArr:[],
        exchangeDateWeekArr:[],
        limitTimeBegin:'',
        virtualStock:0,
        weChatVirtualStock:0
      },
      rules:{
        proName:{required:true,message:'请输入礼品名称',trigger:'blur'},
        proCategoryId:{required:true,message:'请选择礼品分组',trigger:'blur'},
        integralCost:{required:true,type:'number',min:0,message:'请输入积分费用',trigger:'blur'},
        cashCost:{required:true,type:'number',min:0,message:'请输入现金费用',trigger:'blur'},
        costValue:{required:true,type:'number',min:0,message:'请输入礼品成本',trigger:'blur'},
        memberGradeArr:{required:true,type:'array',min:0,message:'请选择适用会员',trigger:'blur'},
      },
      memberGradeOptions:[],
      categoryOptions:[],
      exchangeDateWeekOptions:['1','2','3','4','5','6','7'],
      monthOptions:Array.from(Array(31), (v,k) =>(k+1).toString()),
      sendChildData:{
        storeType:0,
        storeGroupIds:'',
        storeIds:[],
      },
      timeRangeList:[{}],
      isLimitTimes:false,
      isAdd: this.$route.meta.type === 'add',
      isEdit: this.$route.meta.type === 'edit',
      isInfo: this.$route.meta.type === 'info',
    }
  },
  created () {
    this.getGradeList();
    this.getCategoryList();
    // 解决响应式问题
    if (!this.timeRangeList) {
      this.$set(this.timeRangeList,0,{timeRange:['','']})
    }
    if (this.isEdit || this.isInfo) {
      this.getIntegralMallProInfo();
    }
  },
  computed:{
    asideShow() {
      return this.$store.state.marketing.asideShow
    }
  },
  watch:{
    'form.limitTimes'(val) {
      this.isLimitTimes = (val > 0);
    },
  },
  methods:{
    async getIntegralMallProInfo() {
      let res = await getIntegralMallProInfo({integralMallProId:this.$route.params.id});
      if (res.errorCode === 0) {
        const result = res.result;
        this.form.integralMallProId = result.integralMallProId || '';
        this.form.proReferId = result.proReferId || '';
        this.form.proName = result.proName || '';
        this.form.giftImg = {
          imgUrl: result.giftImageUrls || '',
          code: result.giftImageFiledCodes || '',
        };
        this.form.proCategoryId = result.proCategoryId || '';
        this.form.integralCost = result.integralCost || 0;
        this.form.cashCost = result.cashCost || 0;
        this.form.costValue = result.costValue || 0;
        this.form.memberGradeArr = result.memberGrade?result.memberGrade.split(','):[];
        this.form.limitTimes = result.limitTimes || 0;
        this.form.exchangeDateType = result.exchangeDateType || 1;
        this.form.exchangeTimeType = result.exchangeTimeType || 1;
        this.form.proShowStatus = result.proShowStatus || 1;
        this.form.changeType = result.changeType || 2;
        this.form.releaseType = result.releaseType || 1;

        this.form.exchangeFixDate = [result.exchangeFixDateBegin || '',result.exchangeFixDateEnd || ''];
        this.form.exchangeDateDayArr = result.exchangeDateDay ? result.exchangeDateDay.split(',') : [];
        this.form.exchangeDateWeekArr = result.exchangeDateWeek ? result.exchangeDateWeek.split(',').filter(v => v) : [];
        this.form.limitTimeBegin = result.limitTimeBegin || '';
        this.form.weChatVirtualStock = this.form.virtualStock = result.virtualStock || 0;



        // result.showStore = 2;
        this.sendChildData.storeType = result.showStore || 0;



        if (result.showStore === 1) {
          this.sendChildData.storeGroupIds = result.storeGroupIds || '';
        } else if (result.showStore === 2) {
          let list = [];
          if (result.storeInfo.length) {
            result.storeInfo.map(v => {
              list.push(v);
            })
          }
          this.sendChildData.storeIds =  list;
        }

        console.log(this.sendChildData)


        if (this.form.exchangeTimeType === 2 && result.timeZones) {
          let list = result.timeZones.split('#').filter(v => v);
          list.map((v,i)=> {
            let arr = v.split('-');
            this.$set(this.timeRangeList,i,{timeRange:[arr[0],arr[1]]})
          });


        }
      }
    },
    //门店分组回执方法
    getSelectGroupData(val) {
      console.log(val);
      this.sendChildData.storeType = val.storeType || 0
      this.sendChildData.storeGroupIds = val.storeGroupIds || ''
      this.sendChildData.storeIds = val.storeIds || []
    },
    // 获取分类列表
    async getCategoryList() {
      let res = await getCategoryList();
      if (res.errorCode === 0) {
        this.categoryOptions = res.result || [];
      }
    },
    // 新建分类
    createNewGroup() {
      this.$prompt('请输入分组名称', '新建分组', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder:'请输入分组名称',
        inputErrorMessage:'分组名称不能为空',
        inputValidator:function(value) {
          return !!value;
        }
      }).then(({ value }) => {
        createCategoryService({categoryName:value}).then(res => {
          if (res.errorCode === 0) {
            this.$tips({type:'success',message:'新建分组成功'});
            this.getCategoryList();
          } else {
            this.$tips({type:'error',message:'新建分组失败'});
          }
        })
      }).catch(err => {
        console.log(err);
      });
    },
    async getGradeList() {
      let res = await getGradeList();
      if (res.errorCode === 0) {
        this.memberGradeOptions = res.result || [];
      }
      console.log(res);
    },
    // 获取卡券组件回调的对象
    getCardActiveObjFun(val) {
      this.form.weChatVirtualStock = val.couponStock || 0;
      this.form.proReferId = val.coupCardId || '';
      console.log(val)
    },
    addTimeRange() {
      let length = this.timeRangeList.length;
      this.$set(this.timeRangeList,length,{timeRange:['','']})
    },
    delTimeRange(index) {
      this.timeRangeList.splice(index,1);
    },
    submit() {

      if (this.cashCost - this.costValue < 0) {
        this.$tips({type:'warning',message:'礼品成本要大于等于现金费用'});
        return;
      }

      console.log(this.timeRangeList)
      let params = {
        integralMallProId:this.form.integralMallProId || '',
        proType:2, // 商品类型 1 优惠券，2礼品，3实物
        proName:this.form.proName, // 商品名字，优惠券就是所选券的名字。
        proReferId:this.isAdd?'':this.form.proReferId, // 关联的卡券或者礼品
        proCategoryId:this.form.proCategoryId, //礼品的分类
        proShowStatus:this.form.proShowStatus, // 商品显示状态 1:上架状态就显示 2:兑换状态下显示
        integralCost:this.form.integralCost,// 积分费用
        cashCost:this.form.cashCost, // 现金费用，两位小数
        costValue:this.form.costValue,
        limitTimes:this.form.limitTimes,// 次数限制
        memberGrade:this.form.memberGradeArr.length?this.form.memberGradeArr.join(','):'', // 适用会员，多个，逗号拼接。
        exchangeDateType:this.form.exchangeDateType, // 兑换日期1:全部 2:固定日期 3:每月 4:每周
        exchangeTimeType:this.form.exchangeTimeType, // 兑换时间类型 1:全部 2:部分时段

        releaseType:this.form.releaseType, // 布发状态 1立即 2定时

        changeType:this.form.changeType, // 兑换方式 1:微信兑换 2:快递发货 3:在线发货

        showStore:this.sendChildData.storeType, // 显示门店 0所有 1部分分组 2部分门店

        storeIds:'', // 选中的门店信息，多个逗号拼接
        giftImageUrls:this.form.giftImg.imgUrl, // 礼品图片
        giftImageFiledCodes:this.form.giftImg.code, // 礼品图片编码
        virtualStock:this.form.changeType === 1 ? this.form.weChatVirtualStock : this.form.virtualStock, //库存
      }

      // 判断 兑换日期
      if (params.exchangeDateType === 2) {
        if (this.form.exchangeFixDate) {
          params.exchangeFixDateBegin = formateDateTimeByType(this.form.exchangeFixDate[0],'yyyy-MM-dd-HH-mm-ss');
          params.exchangeFixDateEnd = formateDateTimeByType(this.form.exchangeFixDate[1],'yyyy-MM-dd-HH-mm-ss');
        } else {
          this.$tips({type:'warning',message:'兑换固定日期不能为空'});
          return;
        }
      } else if (params.exchangeDateType === 3) {
        params.exchangeDateDay = this.form.exchangeDateDayArr.length > 0 ? this.form.exchangeDateDayArr.join(','):'';
      } else if (params.exchangeDateType === 4) {
        params.exchangeDateWeek  = this.form.exchangeDateWeekArr.length > 0 ? this.form.exchangeDateWeekArr.join(','):'';
      }

      // 判断 兑换时段
      if (params.exchangeTimeType ===  2) {
        let list = [];
        let flag = false;
        this.timeRangeList.forEach(v => {
          if (!v.timeRange || !v.timeRange[0]) {
            flag = true;
          } else {
            list.push(v.timeRange[0]+'-'+v.timeRange[1]);
          }
        })
        if (flag) {
          this.$tips({message:'部分时段未填写完整'});
          return;
        }
        // 如果数组为1的话也要传 #分割
        if (list.length === 1) {
          params.timeZones = list[0] +'#';
        } else {
          params.timeZones =  list.length?list.join('#'):'';
        }
      }




      // 判断发送时间
      if (params.releaseType === 2) {
        params.limitTimeBegin = formateDateTimeByType(this.form.limitTimeBegin,'yyyy-MM-dd-HH-mm-ss');
      }

      // 门店分组
      if (this.sendChildData.storeType === 1) {
        if (this.sendChildData.storeGroupIds) {
          params.storeGroupIds = this.sendChildData.storeGroupIds || '';
        }
      } else if (this.sendChildData.storeType === 2){
        if (this.sendChildData.storeIds) {
          params.storeIds = this.sendChildData.storeIds.map(v => v.storeId).join(',');
        } else {
          params.storeIds ='';
        }
      }








      console.log(params)
      createIntegralProService(params).then(res => {
        if(res.errorCode === 0) {
          this.$router.push('/mall/gift');
          this.$tips({type:'success',message:'操作成功'});
        } else {
          this.$tips({type:'error',message:'操作失败'});
        }
        console.log(res);
      }).catch(err => {
        this.$tips({type:'error',message:'操作失败'});
      })
    }
  }
};
