import { getGradeList, getCategoryList, createIntegralProService, getIntegralMallProInfo, createCategoryService, delCategoryService, getCashCostService } from '@/service/api/mallApi.js';
import cardTemp from '../common/card-temp.vue';
// import dmUploadAvatar from '@/components/upload/avatar';
import { formateDateTimeByType } from '@/utils/index.js';
import tinymceEdit from '../common/tinymce-edit.vue';

export default {
  components: {
    'card-temp': cardTemp,
    tinymceEdit

    // dmUploadAvatar
  },
  data() {
    return {
      form: {
        integralMallProId: '',
        proReferId: '',
        proName: '', // String 商品名字，优惠券就是所选券的名字。 (必填)
        giftImg: {
          //  (必填)
          imgUrl: '', // giftImageUrls
          code: '' // giftImageFiledCodes
        },
        proCategoryId: '', // String 礼品的分类  (必填)
        integralCost: 0, // Number 100 积分费用 (必填)
        cashCost: 0, // Number 现金费用，两位小数
        costValue: 0, // Number 礼品成本，两位小数
        memberGradeArr: [], // array 适用会员 这里是数组 传给后台要拼接为字符串数组逗号隔开
        limitTimes: 0,
        exchangeDateType: 1,
        exchangeTimeType: 1, // 兑换时间类型 1:全部 2:部分时段
        proShowStatus: 1,
        changeType: 2, // Number 兑换方式1:微信兑换 2:快递发货 3:在线发货
        releaseType: 1,
        cardType: 0,
        exchangeFixDate: ['', ''], // exchangeFixDateBegin // exchangeFixDateEnd,
        exchangeDateDayArr: [],
        exchangeDateWeekArr: [],
        limitTimeBegin: '',
        virtualStock: 0,
        weChatVirtualStock: 0,
        detailDescription: '' //图文详情
      },
      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',

      projectName: 'gic-web', // 当前项目名(必传参数)
      wxFlag: '1', // '1': 表示需要返回微信图片地址(可选参数),插件内已默认 '1'
      imgRate: '1:1', // 限制图片上传比例 如 '1:1' (可选参数),各个调用地方可能不同,(比例和限制宽高是二选一的,如果都不传参数,表示不限制)
      limitW: 750, // 上传图片的限制宽度(数字),(可选参数),各个调用地方可能不同
      limitH: 750, // 上传图片的限制高度(数字),(可选参数),各个调用地方可能不同
      actionUrl: '/api-plug/upload-img', // 必选参数，上传的相对地址 String 类型,切勿硬编码写死地址
      maxlength: 5, // 图片数量 默认 5
      imgSize: 1, // 图片大小限制 MB
      imageList: [] // 是否显示已上传文件列表
    };
  },
  watch: {
    'form.limitTimes'(val) {
      this.isLimitTimes = val > 0;
    }
  },
  created() {
    this.$store.commit('mutations_breadcrumb', [{ name: '积分商城' }, { name: '礼品', path: '/coupon' }, { name: this.isAdd ? '新增礼品' : '编辑礼品', path: '' }]);
    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;
    }
  },
  methods: {
    // 删除分类
    deleteCategory(id) {
      delCategoryService({ integralMallCategoryId: id }).then(res => {
        if (res.errorCode === 0) {
          this.getCategoryList();
          this.$tips({ type: 'success', message: '删除分类成功' });
        } else {
          this.$tips({ type: 'error', message: '删除分类失败' });
        }
      });
    },
    // 获取分类列表
    async getCategoryList() {
      let res = await getCategoryList();
      if (res.errorCode === 0) {
        this.categoryOptions = res.result || [];
      }
    },
    // 新建分类
    createCategory() {
      this.$prompt('', '新建分类', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入分类名称',
        inputErrorMessage: '分类名称不能为空',
        inputValidator: function(value) {
          if (!value) {
            return false;
          } else if (value.replace(/[^\x00-\xff]/gi, '--').length > 24) {
            return '中文限制12字，数字字母限制23字符';
          } else {
            return true;
          }
        }
      })
        .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 => {});
    },
    // 获取礼品详情
    /* eslint-disable */
    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.imageList =
          result.images &&
          result.images.map(v => ({
            url: v.imageUrl,
            code: v.imageFieldCode
          }));
        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;
        this.form.detailDescription = result.detailDescription; //图文详情的数据
        this.form.cardType = result.cardType;
        // 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;
        }

        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]] });
          });
        }
        this.isLimitTimes = this.form.limitTimes > 0;
        this.form.costValue = result.costValue || 0;
        this.$nextTick(_ => {
          this.$refs.cardTemp.getCardList();
        });
      }
    },
    //门店分类回执方法
    getSelectGroupData(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 || [];
      }
    },
    // 获取卡券组件回调的对象
    getCardActiveObjFun(val) {
      if (val.hasOwnProperty('cardType')) {
        this.form.cardType = val.cardType;
      }
      if (this.isAdd) {
        this.form.weChatVirtualStock = val.couponStock || 0;
        this.form.proReferId = val.coupCardId || '';
        (async () => {
          let res = await getCashCostService({ coupCardId: val.coupCardId, proType: 1 });
          this.form.costValue = res.result.costValue || 0;
        })();
      }
    },

    // 新增兑换时段-部分时段
    addTimeRange() {
      let length = this.timeRangeList.length;
      if (length >= 5) {
        this.$tips({ type: 'warning', message: '最多五个时间段' });
        return;
      }
      this.$set(this.timeRangeList, length, { timeRange: ['', ''] });
    },
    // 删除兑换时段-部分时段
    delTimeRange(index) {
      this.timeRangeList.splice(index, 1);
    },
    // 提交验证
    submit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.submitService();
        }
      });
    },
    // 提交保存
    submitService() {
      this.form.detailDescription = this.$refs.tinymceWrap.tinymceHtml;
      if (this.form.costValue < this.form.cashCost) {
        this.$tips({ type: 'warning', message: '现金费用不能大于礼品成本' });
        return;
      }
      if (!this.imageList.length) {
        this.$tips({ type: 'warning', message: '礼品主图不能为空' });
        return;
      }
      if (this.form.changeType === 1 && !this.form.proReferId) {
        this.$tips({ type: 'warning', message: '请选择优惠券' });
        return;
      }
      if (this.form.detailDescription) {
        if (this.form.detailDescription.length > 2000) {
          this.$tips({ type: 'error', message: '图文详情编辑超过字数限制' });
          return;
        }
      } else {
        this.form.detailDescription = '';
      }

      let params = {
        integralMallProId: this.form.integralMallProId || '',
        proType: this.form.changeType === 1 ? 2 : 3, // 商品类型 1 优惠券，2礼品，3实物
        proName: this.form.proName, // 商品名字，优惠券就是所选券的名字。
        proReferId: 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.isLimitTimes ? this.form.limitTimes : -1, // 次数限制
        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部分门店
        giftImageUrls: this.imageList
          .map(v => v.url)
          .filter(v => v)
          .join(','), // 礼品图片
        giftImageFiledCodes: this.imageList
          .map(v => v.code)
          .filter(v => v)
          .join(','), // 礼品图片编码

        storeIds: '', // 选中的门店信息，多个逗号拼接
        virtualStock: this.form.changeType === 1 ? this.form.weChatVirtualStock : this.form.virtualStock, //库存
        detailDescription: this.form.detailDescription, //图文详情
        cardType: this.form.cardType
      };

      // 判断 兑换日期
      if (params.exchangeDateType === 2) {
        if (this.form.exchangeFixDate && this.form.exchangeFixDate[0]) {
          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) {
        if (this.form.exchangeDateDayArr.length > 0) {
          params.exchangeDateDay = this.form.exchangeDateDayArr.join(',');
        } else {
          this.$tips({ type: 'warning', message: '兑换每月日期不能为空' });
          return;
        }
      } else if (params.exchangeDateType === 4) {
        if (this.form.exchangeDateWeekArr.length > 0) {
          params.exchangeDateWeek = this.form.exchangeDateWeekArr.join(',');
        } else {
          this.$tips({ type: 'warning', message: '兑换每周日期不能为空' });
          return;
        }
      }

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

        let breakFlag = false;
        for (let i = 0; i < arr.length; i++) {
          if (breakFlag) {
            break;
          }
          const p1 = arr[i];
          for (let j = i + 1; j < arr.length; j++) {
            const p2 = arr[j];
            if ((p2[0] > p1[0] && p2[0] < p1[1]) || (p2[1] > p1[0] && p2[1] < p1[1]) || (p1[0] > p2[0] && p1[0] < p2[1]) || (p1[1] > p2[0] && p1[1] < p2[1])) {
              breakFlag = true;
              break;
            }
          }
        }
        if (breakFlag) {
          this.$tips({ type: 'warning', message: '兑换时段之间不允许出现时间交叠' });
          return;
        }
      }

      // 判断发送时间
      if (params.releaseType === 2) {
        if (this.form.limitTimeBegin) {
          params.limitTimeBegin = formateDateTimeByType(this.form.limitTimeBegin, 'yyyy-MM-dd-HH-mm-ss');
        } else {
          this.$tips({ type: 'warning', message: '定时发布时间不能为空' });
          return;
        }
      }

      // 门店分类
      if (this.sendChildData.storeType === 1) {
        if (this.sendChildData.storeGroupIds) {
          params.storeGroupIds = this.sendChildData.storeGroupIds || '';
        } else {
          this.$tips({ type: 'warning', message: '门店分类不能为空' });
          return;
        }
      } else if (this.sendChildData.storeType === 2) {
        if (this.sendChildData.storeIds.length) {
          params.storeIds = this.sendChildData.storeIds.map(v => v.storeId).join(',');
        } else {
          params.storeIds = '';
          this.$tips({ type: 'warning', message: '部分门店不能为空' });
          return;
        }
      }
      createIntegralProService(params)
        .then(res => {
          if (res.errorCode === 0) {
            this.$router.push('/gift');
            this.$tips({ type: 'success', message: '操作成功' });
          } else {
            this.$tips({ type: 'error', message: '操作失败' });
          }
        })
        .catch(err => {
          this.$tips({ type: 'error', message: '操作失败' });
        });
    },
    // 上传成功 返回的图片对象 里面有图片 大小 类型 等相关信息
    uploadOnSuccess(obj) {
      // 目前返回两个参数 {res:res,file:file}
      obj.file.url = obj.res.result[0] && obj.res.result[0].qcloudImageUrl;
      obj.file.code = obj.res.result[0] && obj.res.result[0].imageFiledCode;
      this.imageList.push(obj.file);
    },
    // 删除图片 返回图片列表的索引 你可以根据这个索引去找对应图片的id
    deleteImage(i) {
      this.imageList.splice(i, 1);
    },
    // 排序图片
    sortImg(val) {
      this.imageList = val;
    }
  }
};
