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 商品名字，优惠券就是所选券的名字。 (必填)
        integralCost:100, // Number 100 积分费用 (必填)
        cashCost:1, // Number 现金费用，两位小数
        memberGradeArr:[],  // array 适用会员 这里是数组 传给后台要拼接为字符串数组逗号隔开
        limitTimes:0,
        exchangeDateType:1,
        exchangeTimeType:1, // 兑换时间类型 1:全部 2:部分时段
        proShowStatus:1,
        releaseType:1,

        exchangeFixDate:['',''], // exchangeFixDateBegin // exchangeFixDateEnd,
        exchangeDateDayArr:[],
        exchangeDateWeekArr:[],
        limitTimeBegin:'',
        virtualStock:0,
        weChatVirtualStock:0
      },
      rules:{
        integralCost:{required:true,type:'number',min:0,message:'请输入积分费用',trigger:'blur'},
        cashCost:{required:true,type:'number',min:0,message:'请输入现金费用',trigger:'blur'},
        memberGradeArr:{required:true,type:'array',min:0,message:'请选择适用会员',trigger:'blur'},
      },
      memberGradeOptions:[],
      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();
    // 解决响应式问题
    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.integralCost = result.integralCost || 0;
        this.form.cashCost = result.cashCost || 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.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.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 getGradeList() {
      let res = await getGradeList();
      if (res.errorCode === 0) {
        this.memberGradeOptions = res.result || [];
      }
      console.log(res);
    },
    // 获取卡券组件回调的对象
    getCardActiveObjFun(val) {
      this.form.virtualStock = 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() {

      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, // 关联的卡券或者礼品
        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定时

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

        storeIds:'', // 选中的门店信息，多个逗号拼接
        virtualStock: this.form.virtualStock, //库存
      }

      // 判断 兑换日期
      if (params.exchangeDateType === 2) {
        params.exchangeFixDateBegin = formateDateTimeByType(this.exchangeFixDate[0],'yyyy-MM-dd-HH-mm-ss');
        params.exchangeFixDateEnd = formateDateTimeByType(this.exchangeFixDate[1],'yyyy-MM-dd-HH-mm-ss');
      } 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;
        }
        params.timeZones =  list.length?list.join('#'):'';
      }




      // 判断发送时间
      if (params.releaseType === 2) {
        this.limitTimeBegin = this.form.exchangeDateWeekArr.length > 0 ? this.form.exchangeDateWeekArr.join(','):'';
      }

      // 门店分组 todo
      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 => {
        this.$router.push('/mall/coupon');
        console.log(res);
      })
    }
  }
};
