<template>
  <div class="p20" v-loading="loading">
    <el-form :model="ruleForm" ref="ruleForm" class="shelf-form pt10 pb10" :rules="rules" label-width="120px">
      <el-form-item label="计划名称" prop="title">
        <dm-input v-model="ruleForm.title" :byte-type="1" :maxlength="15" class="w380" />
      </el-form-item>
      <el-form-item label="计划时间" prop="timeType">
        <el-radio :disabled="disabled" v-model="ruleForm.timeType" :label="1">长期有效</el-radio>
        <el-radio :disabled="disabled" v-model="ruleForm.timeType" :label="2">选择时间段</el-radio>
      </el-form-item>
      <el-form-item v-if="ruleForm.timeType == 2">
        <el-date-picker :disabled="disabled" class="w400" :picker-options="pickerOptions" v-model="dateTime" type="daterange" range-separator="~" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="领取限制" prop="setType">
        <el-radio :disabled="disabled" v-model="ruleForm.setType" :label="1">统一设置</el-radio>
        <el-radio :disabled="disabled" v-model="ruleForm.setType" :label="2">每张卡券单独设置</el-radio>
      </el-form-item>
      <div>
        <shelf-limit ref="shelfLimit1" v-show="ruleForm.setType == 1" />
        <!-- 选择卡券 -->
        <el-form-item v-show="ruleForm.setType == 1" label="选择卡券" class="mt20 is-required">
          <div v-for="(item, idx) in couponList" :key="idx">
            <div class="w400 inline-block" style="min-height:177px;">
              <dm-card-select v-if="item" :coupon-id="item" read-only class="card-select" style="width:400px;display:inline-block;margin-bottom:10px;" :member-card-id="currentAreaId" fix-member-card :unuse-list="couponList" />
            </div>
            <i class="el-icon-delete ml10" @click="couponList.splice(idx, 1)" v-if="item && !disabled"></i>
          </div>
          <el-button class="dashed w400" icon="el-icon-plus" @click="addCouponList" v-if="!disabled">添加卡券</el-button>
        </el-form-item>
      </div>
      <div v-show="ruleForm.setType == 2" style="width: 800px;margin-left:120px;">
        <el-table :data="timeType2List" class="mb20">
          <el-table-column label="卡券名称" show-overflow-tooltip prop="couponName" min-width="150" fixed="left"></el-table-column>
          <el-table-column label="领取时段" min-width="180">
            <template slot-scope="scope">{{ delTimeType(scope.row) }}</template>
          </el-table-column>
          <el-table-column label="领取人群" min-width="140">
            <template slot-scope="scope">
              {{ scope.row.memberSearchId ? '部分人群' : '全部人群' }}
              <el-button type="text" class="ml5" icon="el-icon-view" @click="viewMember(scope.row)" v-if="scope.row.memberSearchId && !isAdd"></el-button>
            </template>
          </el-table-column>
          <el-table-column label="领取限制" min-width="140">
            <template slot-scope="scope">{{ scope.row.getNumType == 1 ? '1' : scope.row.getNum }}/张每人</template>
          </el-table-column>
          <el-table-column label="操作" min-width="130" v-if="!disabled">
            <template slot-scope="scope">
              <el-button type="text" @click="editTimeType2List(scope.row, scope.$index)">编辑</el-button>
              <el-button type="text" @click="timeType2List.splice(scope.$index, 1)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button icon="el-icon-plus" class="dashed width100" v-if="!disabled" @click="showSfDialog">添加单张卡券设置</el-button>
      </div>
      <el-form-item :class="`${disabled ? 'pt20' : 'pt30'}`">
        <el-button type="primary" @click="submitForm">{{ isAdd ? '确认新建' : '保存' }}</el-button>
        <el-button @click="$router.go(-1)">返回</el-button>
      </el-form-item>
    </el-form>
    <shelf-dialog ref="dialog" :dialog-visible.sync="dialogVisible" @saveItem="saveItem" :time-type2list="timeType2List" :unuse-list="couponList2" />
    <div class="hidden">
      <dm-card-select :before-submit="beforeSubmit" ref="cardSelect" read-only :member-card-id="currentAreaId" @selectData="(val) => { selectData(val, idx) }" fix-member-card :unuse-list="couponList" />
    </div>
    <member-view-dialog v-if="!isAdd" :dialog-visible.sync="memberView.dialogVisible" :member-search-id="memberView.memberSearchId" />
  </div>
</template>

<script>
import api from '@/api/gic-card.js';
import { formatDateTimeByType, easyUnique } from '@/utils/index.js';
const { saveShelf, getShelfInfo } = api;
import shelfLimit from './module/shelf-limit';
import { getTimeType } from '@/config/mapping/gic-card';
import shelfDialog from './module/shelf-dialog';
// import memberViewDialog from '@/components/libs/member-view-dialog.vue';
export default {
  name: 'ShelfForm',
  components: {
    shelfLimit,
    shelfDialog,
    // memberViewDialog
  },
  provide() {
    return {
      parentDisabled: () => this.disabled
    };
  },
  data() {
    return {
      loading: false,
      dateTime: '',
      dialogVisible: false,
      couponShelfId: this.$route.query.id,
      ruleForm: {
        title: '',
        timeType: 1, // 1不限时间2时间段
        setType: 1, // 1统一设置2单张设置
      },
      rules: {
        title: [ { required: true, message: '请输入计划名称', trigger: 'blur' } ],
        timeType: [ { required: true, message: '请选择计划时间', trigger: 'blur' } ],
        setType: [ { required: true, message: '请选择领取限制', trigger: 'blur' } ],
      },
      timeType2List: [],
      couponList: [],
      pickerOptions: {
        disabledDate(val) {
          return Date.now() >= val.getTime() + 24 * 60 * 60 * 1000;
        }
      },
      // 预览部分人群
      memberView: {
        dialogVisible: false,
        memberSearchId: ''
      },
      isAdd: this.$route.meta.type === 'add',
      isEdit: this.$route.meta.type === 'edit',
    };
  },
  created() {
    this.$emit('updateBread', [  { breadName: '福利中心'  }, { breadName: 'GIC卡券' }, { breadName: '卡券展架', breadPath: '/gic-card/shelf/list' }, { breadName: `${this.isAdd ? '新建' : '编辑' }展架` } ]);
  },
  mounted() {
    if(this.isEdit) {
      this.getInfo();
    }
    if(this.isAdd) {
      this.$nextTick(() => {
        this.$refs.shelfLimit1.add();
      });
    }
  },
  methods: {
    viewMember({ memberSearchId }) {
      this.memberView.memberSearchId = memberSearchId;
      this.memberView.dialogVisible = true;
    },
    showSfDialog() {
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.dialog.add();
      });
    },
    delTimeType(row) {
      // 处理限制时段
      if(row.getTimeType == 1) {
        return '不限制';
      } else {
        let str = getTimeType[row.getTimeType].label;
        return str;
      }
    },
    // 编辑单张保存的表格
    editTimeType2List(data, idx) {
      this.dialogVisible = true;
      this.$refs.dialog.edit(data, idx);
    },
    addCouponList() {
      this.$refs.cardSelect.handleShowDialog();
    },
    getInfo() {
      if(this.loading) {
        return;
      }
      this.loading = true;
      getShelfInfo({ shelfId: this.couponShelfId }).then(res => {
        this.loading = false;
        const info = res.result || {};
        this.ruleForm.title = info.title;
        this.ruleForm.timeType = info.timeType || 1;
        this.ruleForm.setType = info.setType || 1;
        if(info.timeType == 2) {
          this.dateTime = [ info.startTime, info.endTime ];
        }
        // 处理info.conditionList
        const conditionList = info.conditionList.map(v => {
          const getTimeJson = JSON.parse(v.getTimeJson).map(v => {
            v.time1 = new Date(2020, 1, 1, v.time1.split(':')[0], v.time1.split(':')[1]);
            v.time2 = new Date(2020, 1, 1, v.time2.split(':')[0], v.time2.split(':')[1]);
            return v;
          });
          v.getTimeJson = getTimeJson;
          v.couponJson = JSON.parse(v.couponJson);
          return v;
        });


        if(this.ruleForm.setType == 1) {
          // 统一设置
          const data = conditionList[0];
          data.getTimeJson = data.getTimeType == 1 ? [] : data.getTimeJson;
          this.$refs.shelfLimit1.edit(data);
          // 设置卡券
          this.couponList = data.couponJson || [];
        } else {
          // 单张设置
          this.timeType2List = conditionList.map(v => {
            v.getTimeJson = v.getTimeType == 1 ? [] : v.getTimeJson;
            v.couponId = v.couponJson[0];
            delete v.couponJson;
            return v;
          });
        }
      }).finally(() => {
        this.loading = false;
      });
    },
    submitForm() {
      if(this.loading) {
        return;
      }
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) {
          PublicMethods.jumpToFormError(); // eslint-disable-line
          return;
        } else {
          let params = { ...this.ruleForm };
          if(params.timeType == 2 && !this.dateTime ) {
            this.$tips({ message: '请选择计划时间范围', type: 'error' });
            return;
          }
          if(this.ruleForm.setType == 1) {
            // 统一设置
            if(!this.couponList.filter(v => { return v !== ''; }).length) {
              this.$tips({ message: '至少选择一张卡券', type: 'error' });
              return;
            }
            if(easyUnique(this.couponList).length !== this.couponList.length) {
              this.$tips({ message: '卡券不能重复', type: 'error' });
              return;
            }
            let data = this.$refs.shelfLimit1.dealData();
            if(!data) {
              return;
            }
            data.couponJson = this.couponList.filter(v => v);
            params.shelfCouponInfo = [ data ];

          } else {
            if(!this.timeType2List.length) {
              this.$tips({ message: '请设置单张卡券数据', type: 'error' });
              return;
            }
            // 单张设置
            if(easyUnique(this.timeType2List.map(v => v.couponId)).length !== this.timeType2List.length) {
              this.$tips({ message: '卡券不能重复', type: 'error' });
              return;
            }

            params.shelfCouponInfo = this.timeType2List.map(v => {
              v.couponJson = [ v.couponId ];
              delete v.couponId;
              return v;
            });
          }
          params.shelfCouponInfo = JSON.stringify(params.shelfCouponInfo);
          params.memberCardId = this.currentAreaId;
          // 处理时间段
          if(params.timeType == 2) {
            params.startTime = formatDateTimeByType(this.dateTime[0]);
            params.endTime = formatDateTimeByType(this.dateTime[1]);
          }
          // console.log(params);
          // return;
          this.loading = true;
          if(this.isEdit) {
            params.couponShelfId = this.couponShelfId; // 编辑
          }
          saveShelf(params).then(res => {
            this.loading = false;
            this.$tips({ message: '操作成功', type: 'success' });
            this.$router.push('/gic-card/shelf/list');
          }).finally(() => {
            this.loading = false;
          });
        }
      });
    },
    saveItem(idx, data) {
      if(idx === '' || idx == undefined) {
        // 新增的
        this.timeType2List.push(data);
      } else {
        // 编辑
        this.timeType2List.splice(idx, 1, data);
      }
    },
    // 卡券选择器
    beforeSubmit(id) {
      if(this.couponList.includes(id)) {
        this.$tips({ message: '该卡券已存在', type: 'error' });
        return false;
      }
      return true;
    },
    selectData(data, idx, flag = false) {
      this.couponList.push(data.couponId);
    },
  },
  computed: {
    disabled() {
      // 编辑 (选择时间段 已过开始时间生效/过期) || (长期有效)
      const flag = this.ruleForm.timeType === 1 || (this.ruleForm.timeType === 2 && new Date() >= new Date(this.dateTime[0]));
      return this.isEdit && flag;
    },
    // 每张卡券单独设置的禁用卡券列表
    couponList2() {
      return this.timeType2List.map(v => v.couponId);
    },
  },
};
</script>

<style lang="scss" scoped>
.el-icon-delete {
  display: inline-block;
  font-size: 17px;
  padding: 9px;
  margin-right: 10px;
  color: #909399;
  border: 1px solid #e4e7ed;
  border-radius: 50%;
  vertical-align: middle;
  cursor: pointer;
  position: relative;
  top: -60px;
  &:hover {
    background:rgba(254,240,240,1);
    border:1px solid rgba(251,196,196,1);
    color: #F5222D;
  }
}
</style>