<template>
  <div class="p20" v-loading="loading">
    <el-form :model="ruleForm" ref="ruleForm" :rules="rules" label-width="160px">
      <h3 class="pb20">自提点信息</h3>
      <el-form-item label="自提点类型">
        <el-radio v-model="ruleForm.type" :label="1">从门店中选择</el-radio>
      </el-form-item>
      <el-form-item v-if="isAdd" prop="storeWidgetId" label="门店选择器">
        <dm-store-select :selector-id="ruleForm.storeWidgetId" @save="saveStore"></dm-store-select>
      </el-form-item>
      <template v-else>
        <el-form-item label="自提点名称" required>
          <el-input v-model="info.name" class="w600" type="text" disabled> </el-input>
        </el-form-item>
        <el-form-item label="联系电话" required>
          <el-input v-model="info.phone" class="w600" type="text" disabled> </el-input>
        </el-form-item>
        <el-form-item label="自提点地址" required>
          <el-input v-model="info.address" class="w600" type="text" disabled> </el-input>
        </el-form-item>
        <el-form-item label="自提点图片" required>
          <img style="width: 150px; height: 150px" :src="info.imageUrl" draggable="false" />
        </el-form-item>
        <el-form-item label="营业时间">
          <div v-for="(item, index) in info.businessHour" :key="index" class="time-list">
            <el-select v-model="item.weekdayShow" multiple placeholder="请选择" disabled class="mr10">
              <el-option :label="item" :value="item" :key="item" v-for="item in ['周一', '周二', '周三','周四','周五','周六','周日']"></el-option>
            </el-select>
            <el-time-select placeholder="起始时间" v-model="item.openTime" disabled style="width:170px" class="mr10"></el-time-select>
            <span style="font-size:14px;margin-right:10px;">至</span>
            <el-time-select placeholder="起始时间" v-model="item.closeTime" disabled style="width:170px"></el-time-select>
          </div>
        </el-form-item>

      </template>
      <h3 class="pt20 pb20">自提点设置</h3>
      <form-content :rule-form.sync="ruleForm"></form-content>
      <el-form-item class="mt20">
        <el-button @click="handleSubmit()" type="primary">{{ isAdd ? '确认新建' : '保存' }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import fetch from '@/api/gift.js';
const { insertPickupStore, getPickupDetails, updatePickupStore } = fetch;
import formContent from './module/pickup-form-content';
import { getSeconds } from '@/utils/common';
import { isEmpty } from '@/utils/index';

export default {
  name: 'PickupForm',
  components: {
    formContent
  },
  data() {

    const validDynamicType = (rule, value, callback) => {
      const { dynamicType, dynamicH, dynamicM, dynamicD } = this.ruleForm;
      if (dynamicType == 1) {
        if(isEmpty(dynamicH) || isEmpty(dynamicM)) {
          callback(new Error('填写不完整'));
          return;
        }
      } else {
        if(isEmpty(dynamicD)) {
          callback(new Error('填写不完整'));
          return;
        }
      }
      callback();
    };
    const validTime = (rule, value, callback) => {
      const { fixedTime } = this.ruleForm;
      if(fixedTime.length == 0) {
        callback(new Error('请配置固定日期范围'));
        return;
      }
      let flag = false;
      fixedTime.forEach(v => {
        if(!(v.dataRange && v.dataRange.length && v.dataRangep[0] && v.dataRange[1])) {
          flag = true;
        }
      });
      if(flag) {
        callback(new Error('请配置固定日期范围'));
        return;
      }
      callback();
    };
    return {
      loading: false,
      pickupId: this.$route.query.id, // 主键
      ruleForm: {
        type: 1,
        chooseTimeFlag: 0,
        dateType: 1, // 日期类型 1、动态日期 2、固定日期
        fixedTime: [ { dataRange: '' } ], // 固定日期
        // 动态日期start
        dynamicType: 1, // 动态日期-类型
        dynamicH: '', // 动态日期-小时
        dynamicM: '', // 动态日期-分钟
        dynamicD: '', // 动态日期-天
        dynamicStop: '', // 停止自提
        // 动态日期end
        storeWidgetId: '', // 门店id
        timeoutDealType: 1, // 超期处理方式：1自动完成核销 2自动关闭发货单
      },
      rules: {
        storeWidgetId: { required: true, message: '请选择门店', trigger: 'change' },
        dynamicType: { required: true, validator: validDynamicType, trigger: 'blur' },
        dynamicStop: { required: true, message: '请填写提货有效期', trigger: 'change' },
        fixedTime: { required: true, validator: validTime, trigger: 'change' },
      },
      info: {
        businessHour: []
      },
      isAdd: this.$route.meta.type === 'add',
      isEdit: this.$route.meta.type === 'edit',
    };
  },
  mounted() {
    if(!this.isAdd) {
      this.getInfo();
    }
  },
  created() {
    this.$emit('updateBread', [  { breadName: '福利中心'  }, { breadName: '通用设置' }, { breadName: '自提点设置', breadPath: '/setting/pickup-list' }, { breadName: this.isAdd ? '新建自提点' : '编辑自提点', breadPath: '' } ]);
  },
  methods: {
    getInfo() {
      this.loading = true;
      getPickupDetails({ pickupId: this.pickupId }).then(res => {
        this.loading = false;
        const info = res.result || {};
        let businessHour = info.businessHour ? JSON.parse(info.businessHour) : [];
        for (let item of businessHour) {
          item.weekdayShow = item.weekdayShow.split('、');
          item.openTime = getSeconds(item.openTime);
          item.closeTime = getSeconds(item.closeTime);
        }
        info.businessHour = businessHour;
        this.info = info;
        // 表单的
        Object.keys(this.ruleForm).map(key => {
          const obj = {};
          if (key in res.result) {
            obj[key] = info[key];
            // this.ruleForm[key] = info[key];
          }
          Object.assign(this.ruleForm, obj);
        });
        if(info.chooseTimeFlag) {
          const pickupDateInfo = JSON.parse(info.pickupDateInfo);
          // 其他的
          if(info.dateType == 1) {
            // 动态日期
            this.ruleForm.dynamicType = pickupDateInfo.setType;
            this.ruleForm.dynamicStop = pickupDateInfo.validite;
            if(pickupDateInfo.setType == 1) {
              this.ruleForm.dynamicH = parseInt(pickupDateInfo.time / 60);
              this.ruleForm.dynamicM = pickupDateInfo.time % 60;
            } else {
              this.ruleForm.dynamicD = pickupDateInfo.time / 60 / 24;
            }
          } else {
            // 固定日期
            this.ruleForm.fixedTime = pickupDateInfo.map(v => {
              return { dataRange: [ v.startTime, v.endTime ] };
            });
          }
        }
      }).catch(() => {
        this.loading = false;
      });
    },
    saveStore(storeWidgetId) {
      this.ruleForm.storeWidgetId = storeWidgetId;
      this.$refs.ruleForm.validateField('storeWidgetId');
    },
    async submit(params) {
      this.loading = true;
      try {
        if(this.isAdd) {
          await insertPickupStore(params);
        } else {
          await updatePickupStore(params);
        }
        this.loading = false;
        this.$router.push('/setting/pickup-list');
        this.$tips({ message: `${this.isAdd ? '新建' : '编辑'}成功`, type: 'success' });
      } catch (error) {
        this.loading = false;
      }
    },
    handleSubmit() {
      if(this.loading) {
        return;
      }
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) {
          PublicMethods.jumpToFormError(); // eslint-disable-line
          return;
        } else {
          // 组装数据
          const { chooseTimeFlag, dateType, storeWidgetId, timeoutDealType, dynamicType, dynamicH, dynamicM, dynamicD, dynamicStop, fixedTime } = this.ruleForm;
          let params = {
            chooseTimeFlag, dateType, storeWidgetId, timeoutDealType
          };
          if(chooseTimeFlag) {
            // pickupDateInfo: 动态日期 {"setType":1,"time":45,"validite":2}；固定日期 json数组[{"endTime":1587168000000,"startTime":1587168000000}]
            if(params.dateType == 1) {
              // 动态日期
              params.pickupDateInfo = {
                setType: dynamicType,
                time: dynamicType == 1 ? dynamicH * 60 + dynamicM : dynamicD * 24 * 60, // 转换为分钟
                validite: dynamicStop
              };
            } else {
              // 固定日期
              params.pickupDateInfo = fixedTime.map(v => {
                return { startTime: new Date(v.dataRange[0]).getTime(), endTime: new Date(v.dataRange[0]).getTime() };
              });
            }
            params.pickupDateInfo = JSON.stringify(params.pickupDateInfo);
          }
          if(this.isEdit) {
            params.ids = this.pickupId;
          }
          this.submit(params);
        }
      });
    }
  },
};
</script>
<style scoped>
.w600 {
  width: 600px;
}
</style>