import api from '@/api/gic-card';
import { predefineColors, cardType } from '@/config/mapping/gic-card';
import { formatDateTimeByType, deepClone, reRreshRoute } from '@/utils/index';
import resultDialog from './module/result-dialog';
import sendPreview from './module/send-preview';
import floor from '@/mixins/floor.js';
import importCode from './module/import-code';
const { cardInfo, updateCard } = api;

// gic审核任何状态 + 微信审核中 === info（只读）
// gic审核成功 + 微信审核失败/成功 === info(可编辑支持项)

export default {
  name: 'card-form-info',
  components: {
    resultDialog,
    sendPreview,
    importCode
  },
  mixins: [ floor ],
  data() {
    return {
      loading: false,
      couponId: this.$route.query.id,
      subapp: {}, // 子应用信息
      info: {}, // 卡券信息
      ruleForm: {
        color: '', // 卡券颜色
        useExplain: '', // 使用说明
        adaptGoodsExplain: '', // 适用商品说明
        adaptStoreExplain: '', // 适用门店说明
      },
      cardType: Object.keys(cardType).map(v => { return cardType[v]; }),
      rules: {
        useExplain: { required: true, message: '使用说明不能为空', trigger: 'blur' },
      },
      predefineColors,
      isInfo: this.$route.meta.type === 'info',
      isEdit: this.$route.meta.type === 'edit',
      // 线下门店适用
      xxsy: {
        switch: false,
        feeLimit: 0,
        onlyFlag: false,
        storeFilterId: '',
        goodsFilterId: '',
      },
      // GIC微商城适用
      gicmall: {
        switch: false,
        feeLimit: 0,
        onlyFlag: false,
        goodsFilterId: '',
        maxDiscountAmount: undefined,
        maxDiscountGoodsCount: undefined,
        shopFilter: []
      },
      floorId: '', // 当前楼层id
      floor: [
        { name: '基本信息', targetId: 'f1' },
        { name: '领取和使用限制', targetId: 'f2' },
        { name: '适用信息', targetId: 'f3' },
      ],
      result: { //
        visible: false,
        title: '',
        info: ''
      },
      submitType: '', // 提交结果 1成功 失败
      // 预览
      preview: {
        visible: false,
        disabled: true
      },
      importVisible: false, // 导入券码model
      fileList: [], // 导入券码的的文件的列表
      linkData: {}, // 首图链接
      linkData2: {}, // 跳转配置
      operAuth: []
    };
  },
  created() {
    this.$emit('updateBread', [  { breadName: '福利中心'  }, { breadName: 'GIC卡券' }, { breadName: '卡券库', breadPath: '/gic-card/list' }, { breadName: this.isInfo ? '卡券详情' : '编辑卡券' } ]);
  },
  mounted() {
    if (this.currentAreaId) {
      // this.handleGetSubAppByInfo();
      this.getCardInfo();
    }
  },
  methods: {
    effectiveDateFormate(item = {}) {
      const { cardEffectiveMode, startDate, expireDate, effectTimeMode, expireTimeCount, effectTimeCount } = item;
      if (cardEffectiveMode === 0) {
        return `${formatDateTimeByType(startDate, 'yyyy-MM-dd')} ~ ${ formatDateTimeByType(expireDate, 'yyyy-MM-dd') }`;
      }
      if (cardEffectiveMode === 1) {
      // 领取后第{{ info.effectTimeCount }}{{ info.effectTimeMode ? '月' : '天' }} - 第{{ info.expireTimeCount + info.effectTimeCount - 1 }}{{ info.effectTimeMode ? '月' : '天' }}
        const unit = effectTimeMode ? '月' : '天';
        let pre = '';
        switch (effectTimeCount) {
          case 1:
            pre = '当';
            break;
          case 2:
            pre = '次';
            break;
          default:
            pre = effectTimeCount;
            break;
        }
        return `领取后${pre}${unit}生效，有效天数${expireTimeCount}${unit}`;
      }
      return '--';
    },
    // 提交表单
    submitForm() {
      if (this.loading) {
        return;
      }
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) {
          PublicMethods.jumpToFormError(); // eslint-disable-line
          return;
        } else {
          let params = deepClone(this.info);
          // 将ruleForm中可编辑项赋值
          params = { ...params, ...this.ruleForm };
          if (!params.cardEffectiveMode) {
            // 固定日期
            params.startDate = formatDateTimeByType(params.startDate, 'yyyy-MM-dd');
            params.expireDate = formatDateTimeByType(params.expireDate, 'yyyy-MM-dd');
          }
          params.applyList = JSON.stringify(params.applyList);
          params.useConditionLimit = JSON.stringify(params.useConditionLimit);
          this.loading = true;
          if (params !== true) {
            return;
          }
          this.$emit('updateLoading', true);
          updateCard(params).then(res => {
            this.$emit('updateLoading', false);
            this.loading = false;
            // this.result.info = this.needCheck ? '卡券保存并提交审核，请尽快通知审核人员进行审核。' : '卡券保存成功';
            this.result.info = '卡券保存成功';
            this.result.title = '操作成功';
            this.result.visible = true;
            this.submitType = 1;
          }).finally(() => {
            this.$emit('updateLoading', false);
            this.loading = false;
          });
        }
      });
    },
    // 提示信息关闭
    handleResClose() {
      if (this.submitType) {
        this.result.visible = false;
        this.$router.push('/gic-card/list');
      } else {
        reRreshRoute();
      }
    },
    // 获取卡券详情  type默认为空 赋值所有数据  传code只重新赋值库存
    getCardInfo(type) {
      this.loading = true;
      this.$emit('updateLoading', true);
      cardInfo({ couponId: this.couponId }).then((res) => {
        if (type === 'code') {
          this.info.couponStock = res.result.couponStock || 0;
          return;
        }
        const info = res.result || {};
        if (info.operAuthType == 2) {
          this.operAuth = info.operAuth.split(',');
        }
        info.useConditionLimit = info.useConditionLimit ? JSON.parse(info.useConditionLimit) : {};
        this.info = info;
        // 给可以编辑的属性赋值
        Object.keys(this.ruleForm).map(key => {
          if (key in info) {
            this.ruleForm[key] = info[key] || '';
          }
        });
        if (this.info.giveFlag && this.info.giveBannerJumpUrl) {
          this.linkData = JSON.parse(this.info.giveBannerJumpUrl);
        }
        if (this.info.cardJumpFlag && this.info.cardJumpLink) {
          this.linkData2 = JSON.parse(this.info.cardJumpLink);
        }
        // 给卡券适用信息赋值
        info.applyList.forEach(v => {
          const { applyType, feeLimit, onlyFlag, maxDiscountAmount, maxDiscountGoodsCount, goodsFilterId, storeFilterId, shopFilter } = v;
          if (applyType === 1) {
            // 线下适用
            this.xxsy = {
              switch: true,
              feeLimit,
              onlyFlag,
              storeFilterId,
              goodsFilterId,
            };
          }
          if (applyType === 2) {
            let shop;
            if (shopFilter) {
              shop = JSON.parse(shopFilter).map(v => {
                return `${v.name}(id:${v.id.slice(-5)})`;
              });
            }
            // GIC微商城适用
            this.gicmall = {
              switch: true,
              feeLimit,
              onlyFlag,
              goodsFilterId,
              maxDiscountAmount,
              maxDiscountGoodsCount,
              shopFilter: shop
            };
          }
        });
        this.loading = false;
        this.$emit('updateLoading', false);
      }).finally(() => {
        this.$emit('updateLoading', false);
        this.loading = false;
      });
    },
    // 关闭导入券码弹窗
    importCodeSuccess() {
      this.getCardInfo('code');
    },
    // ***********门店选择器***************
    passStoreNewId(res) {
      if (this.isEdit) {
        this.xxsy.storeFilterId = res.storeWidgetId || '';
      }
    },
  },
  computed: {
    needCheck() {
      if (this.subapp.config) {
        if (this.isEdit) {
          return !!this.subapp.config.couponUpdate;
        }
      }
      return false;
    }
  },
};