<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-04-13 15:27:46
 * @LastEditors: 无尘
 * @LastEditTime: 2020-04-27 10:28:59
 -->

<template>
  <section class="common-right-wrap">
    <div class="new-card-body border-box">
      <el-form :model="formData" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
        <el-form-item label="卡券组合名称" prop="cardCombineName">
          <limitInput :inputWidth="340" :disflag="$route.query.repairId ? true : false" :inputValue.sync="formData.cardCombineName" :getByType="'word'" :holder="'请输入卡券组合名称'" :maxLength="20"> </limitInput>
        </el-form-item>
        <div class="item-title font-14 color-303133 font-w-600">卡券选择策略</div>
        <div class="el-form-item el-form-item--large is-required">
          <label for="name" class="el-form-item__label" style="width: 120px; cursor: pointer;">
            <el-tooltip class="item" effect="dark" content="支持多选，最多可选20个模板" placement="top-start"> <span style="cursor: pointer;padding-bottom: 2px; border-bottom: 1px dashed #2F54EB;">选择卡券模板</span></el-tooltip>
          </label>
          <div class="el-form-item__content" style="margin-left: 120px;">
            <div :class="['card-add-btn text-center ', $route.query.repairId ? 'cursor-not-allowed' : 'cursor-pointer']" @click="showCardTemp"><span class="font-14 color-606266">选择卡券模板</span></div>
            <div v-if="formData.cardTemplateJson.length" class="m-t-20">
              <el-table class="select-table" max-height="450" :data="formData.cardTemplateJson" tooltip-effect="dark" :style="{ width: '100%' }">
                <el-table-column label="卡券模板名称" show-overflow-tooltip>
                  <template slot-scope="scope">{{ scope.row.templateName }}</template>
                </el-table-column>
                <el-table-column prop="" label="卡券类型">
                  <template slot-scope="scope">
                    <span v-if="scope.row.cardType == 0">抵金券</span>
                    <span v-if="scope.row.cardType == 1">折扣券</span>
                  </template>
                </el-table-column>
                <el-table-column prop="" label="有效期" width="505">
                  <template slot-scope="scope">
                    <el-select :disabled="$route.query.repairId ? true : false" class="w-100" v-model="scope.row.effectiveType" placeholder="">
                      <el-option label="固定日期" value="0"></el-option>
                      <el-option label="发送后" value="1"></el-option> </el-select
                    ><el-date-picker :disabled="$route.query.repairId ? true : false" v-if="scope.row.effectiveType == 0" class="m-l-10 w-300 vertical-middle" prefix-icon="el-icon-time" :picker-options="pickerOptions" v-model="scope.row.dateRange" @change="changeDate" :editable="false" :value-format="'yyyy-MM-dd'" type="daterange" align="right" unlink-panels range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"> </el-date-picker> <el-select :disabled="$route.query.repairId ? true : false" class="w-100 m-l-10" v-if="scope.row.effectiveType == 1" v-model="scope.row.sendNumberDay" placeholder="请选择"> <el-option v-for="item in dateOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option> </el-select><span class="font-14 color-606266 p-l-10" v-if="scope.row.effectiveType == 1">有效，有效天数</span><el-input-number class="w-100 m-l-10" v-if="scope.row.effectiveType == 1" v-model="scope.row.effectiveDay" controls-position="right" :min="1" :max="366"></el-input-number><span class="font-14 color-606266 p-l-10" v-if="scope.row.effectiveType == 1">天</span>
                  </template>
                </el-table-column>
                <el-table-column prop="" label="发送总数" width="350">
                  <template slot-scope="scope">
                    {{ scope.row.sendLimit }}
                    <!-- <el-select :disabled="$route.query.repairId ? true : false" class="w-100" v-model="scope.row.limitType" placeholder=""> <el-option label="限制总数" value="0"></el-option> </el-select><el-input-number :disabled="$route.query.repairId ? true : false" class="w-100 m-l-10 vertical-middle" v-model="scope.row.dateDayNum" controls-position="right" :min="1" :max="999999999"></el-input-number> -->
                  </template>
                </el-table-column>
                <el-table-column prop="" label="操作" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <el-button :disabled="$route.query.repairId ? true : false" type="text" @click="toDelTemp(scope.$index, scope.row, formData.cardTemplateJson)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div v-if="!formData.cardTemplateJson.length && cardErr" class="el-form-item__error">请选择卡券模板</div>
          </div>
        </div>
        <div class="item-title font-14 color-303133 font-w-600">执行策略</div>
        <div class="el-form-item el-form-item--large">
          <label for="name" class="el-form-item__label" style="width: 120px; cursor: pointer;">
            <el-tooltip class="item" effect="dark" content="卡券的发送范围设置" placement="top-start"> <span style="cursor: pointer;padding-bottom: 2px; border-bottom: 1px dashed #2F54EB;">发送范围</span></el-tooltip>
          </label>
          <div class="el-form-item__content" style="margin-left: 120px;">
            <el-radio :disabled="$route.query.repairId ? true : false" v-model="formData.sendRange" label="0" @change="changeSendType">全企业</el-radio><el-radio :disabled="$route.query.repairId ? true : false" class="m-l-40" v-model="formData.sendRange" label="1" @change="changeSendType"><span @click="clickSendType">部分部门</span></el-radio>
            <div v-if="formData.sendRange == 0" class="position-select">
              <div class="position-check"><el-checkbox :disabled="$route.query.repairId ? true : false" v-model="formData.positionFlag">按职务筛选</el-checkbox></div>
              <div class="position-check-tags">
                <el-checkbox :disabled="$route.query.repairId ? true : false" v-model="formData.noPosition" @change="changeNoPosition">无职务</el-checkbox>
                <template v-for="tag in formData.positionNames">
                  <el-tag v-if="tag != -1" :key="tag" closable :disable-transitions="false" @close="handleClose(tag)">
                    {{ tag }}
                  </el-tag>
                </template>

                <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small" maxlength="20" show-word-limit @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm"> </el-input>
                <el-button v-else :disabled="$route.query.repairId ? true : false" class="button-new-tag" size="small" @click="showInput">+ 添加职务</el-button>
              </div>
            </div>
          </div>
        </div>
        <div class="el-form-item el-form-item--large">
          <label for="name" class="el-form-item__label" style="width: 120px; cursor: pointer;">
            发送次数设置
          </label>
          <div class="el-form-item__content" style="margin-left: 120px;">
            <el-radio v-model="formData.fixdType" label="0">定时发送</el-radio>
            <div class="date-valid">
              <el-select :disabled="$route.query.repairId ? true : false" v-model="formData.fixdTimes" placeholder="请选择">
                <el-option v-for="item in timeOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </div>
          </div>
        </div>
        <el-form-item>
          <el-button :disabled="$route.query.repairId ? true : false" type="primary" @click="cancelEdit">取消</el-button>
          <el-button :disabled="$route.query.repairId ? true : false" type="primary" @click="submitForm('ruleForm')">确认{{ $route.query.repairId ? '编辑' : '新建' }}</el-button>
          <el-button v-if="!$route.query.repairId" :disabled="$route.query.repairId ? true : false" type="primary" @click="submitForm('ruleForm', 'flag')">确认并继续新建</el-button>
        </el-form-item>
      </el-form>
    </div>
    <select-card-template :cardTempShow="cardTempShow" :selectTemp="formData.cardTemplateJson" @returnData="returnData" @closeTemp="closeTemp"></select-card-template>
    <select-wx-depart :departShow="departShow" :departArr="formData.departmentJson" @refreshData="refreshData"></select-wx-depart>
  </section>
</template>
<script>
import limitInput from '@/components/limit-input.vue';
import selectCardTemplate from '@/components/app/protectCard/select-card-template.vue';
import selectWxDepart from '@/components/app/protectCard/select-wx-depart.vue';
import { getRequest, postRequest } from '@/api/api';
import showMsg from '@/common/js/showmsg';
import errMsg from '@/common/js/error';
import { _debounce } from '@/common/js/public';
export default {
  name: 'chat-log',
  props: {
    brandId: {
      type: String,
      default() {
        return '';
      }
    },
    activeGroupId: {
      type: String,
      default() {
        return '';
      }
    }
  },
  components: {
    limitInput,
    selectCardTemplate,
    selectWxDepart
  },
  data() {
    return {
      activeBrand: this.brandId, // 商户(品牌) id
      activeGroup: this.activeGroupId, // 商户(品牌) groupId
      activeId: '3',
      wxEnterpriseId: localStorage.getItem('userInfos') ? JSON.parse(localStorage.getItem('userInfos')).wxEnterpriseId : '',
      selectCoupCard: {}, //已选卡券对象
      timeOptions: [
        {
          label: '15分钟后',
          value: '15'
        },
        {
          label: '30分钟后',
          value: '30'
        },
        {
          label: '1小时后',
          value: '60'
        },
        {
          label: '3小时后',
          value: '180'
        }
      ],
      formData: {
        repairId: '',
        cardCombineName: '',
        cardTemplateJson: [
          // {
          //   templateName: '',
          //   cardType: '0',
          // effectiveType: '0',
          // dateRange: [],
          // sendNumberDay: '',
          // sendLimit: '50000',
          // }
        ],
        sendRange: '0',
        positionFlag: false,
        noPosition: false,
        positionNames: [],
        departmentJson: [],
        fixdType: '0',
        fixdTimes: '15'
      },
      cardErr: false,
      rules: {
        // receiveType: [{ validator: validateReceiveType, trigger: 'change' }],
        cardCombineName: [{ required: true, message: '请输入卡券组合名称', trigger: 'blur' }],
        cardTemplateJson: [{ type: 'array', required: true, message: '请至少选择一个卡券模板', trigger: 'change' }]
      },
      cardSelectShow: false,
      choiceDateCopy: [],
      pickerOptions: {
        onPick: ({ maxDate, minDate }) => {
          this.choiceDateCopy = [minDate.getTime()];
          if (maxDate) {
            this.choiceDateCopy = [];
          }
        },
        disabledDate: time => {
          if (this.choiceDateCopy.length) {
            const one = 365 * 24 * 3600 * 1000;
            const minTime = this.choiceDateCopy[0] - one;
            const maxTime = this.choiceDateCopy[0] + one;
            return time.getTime() < minTime || time.getTime() > maxTime || time.getTime() < Date.now() - 8.64e7;
          }
          return time.getTime() < Date.now() - 8.64e7;
          /*  if (this.choiceDateCopy.length) {
            const one = 365 * 24 * 3600 * 1000;
            const minTime = this.choiceDateCopy[0];
            const maxTime = this.choiceDateCopy[0] + one;
            return time.getTime() < minTime || time.getTime() > maxTime || time.getTime() < Date.now() - 8.64e6;
          }
          return time.getTime() < Date.now() - 8.64e6; */
        }
      },
      dateOptions: [],
      monthOptions: [],
      inputVisible: false,
      inputValue: '',
      cardTempShow: false,
      departShow: false
    };
  },
  methods: {
    /*
     * 无职务选择
     */
    changeNoPosition(e) {
      const that = this;
      if (e && that.formData.positionNames.length > 50) {
        that.$message.error({
          duration: 1000,
          message: '最多可添加50个职务'
        });
        that.formData.noPosition = false;
        return false;
      }
      if (!!e) {
        that.formData.positionNames.push('-1');
      } else {
        that.formData.positionNames.splice(that.formData.positionNames.indexOf('-1'), 1);
      }
    },
    /**
     *  修改发送类型
     */
    changeSendType() {
      const that = this;
      if (that.formData.sendRange == 1) {
        that.departShow = true;
      } else {
        that.departShow = false;
      }
    },
    clickSendType() {
      const that = this;
      that.departShow = true;
    },
    refreshData(data) {
      const that = this;
      that.departShow = false;
      if (data == 'close') {
        return false;
      }
      that.formData.departmentJson = data;
    },
    /**
     *  取消
     */
    cancelEdit() {
      const that = this;
      that
        .$confirm('是否确认返回，返回后当前页面内容将丢失', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.$router.go(-1);
        })
        .catch(() => {});
    },
    /**
     *  选择卡券模板
     */
    showCardTemp() {
      const that = this;
      if (that.$route.query.repairId) {
        return false;
      }
      that.cardTempShow = true;
    },
    /**
     *  选择卡券模板弹窗返回数据
     */
    returnData(data) {
      const that = this;
      data.forEach(ele => {
        ele.effectiveType = '0';
        ele.dateRange = [];
        ele.sendNumberDay = '0';
        ele.sendLimit = '50000';
      });
      that.formData.cardTemplateJson = JSON.parse(JSON.stringify(data));
      that.cardTempShow = false;
    },
    /**
     *  选择卡券模板弹窗关闭
     */
    closeTemp() {
      const that = this;
      that.cardTempShow = false;
    },
    /**
     *  添加职务
     */
    handleClose(tag) {
      const that = this;
      that.formData.positionNames.splice(that.formData.positionNames.indexOf(tag), 1);
    },

    showInput() {
      const that = this;
      if (that.formData.positionNames.length > 50) {
        that.$message.error({
          duration: 1000,
          message: '最多可添加50个职务'
        });
        return false;
      }
      that.inputVisible = true;
      that.$nextTick(_ => {
        that.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      const that = this;
      let inputValue = that.inputValue;
      if (inputValue) {
        that.formData.positionNames.push(inputValue);
      }
      that.inputVisible = false;
      that.inputValue = '';
    },
    /**
     *  删除已选卡券
     */
    toDelTemp(index, row, arr) {
      arr.splice(index, 1);
      // 还要把已选的卡券模板数据处理
    },
    /**
     *  第多少天处理
     */
    handleDay() {
      const that = this;
      let arr = [];
      for (let index = 0; index < 91; index++) {
        if (index == 0) {
          arr.push({
            label: `当天`,
            value: String(index)
          });
        } else {
          arr.push({
            label: `第${index}天`,
            value: String(index)
          });
        }
      }
      that.dateOptions = arr;
      that.monthOptions = [];
      for (let index = 1; index < 13; index++) {
        that.monthOptions.push({
          label: `${index}月`,
          value: String(index)
        });
      }
    },
    /**
     * 选择门店
     */
    returnStores: function(nodes) {
      const that = this;
      console.log('store:', nodes);
      that.formData.selectList = JSON.parse(JSON.stringify(nodes));
    },
    /**
     * 选择门店分组
     */
    checkGroupIds: function(nodes) {
      const that = this;
      console.log(nodes);
      that.formData.selectList = JSON.parse(JSON.stringify(nodes));
    },
    /**
     *  打开选择卡券
     */
    showCard() {
      const that = this;
      that.cardSelectShow = true;
    },
    /**
     *  closeCard
     */
    closeCard() {
      const that = this;
      that.cardSelectShow = false;
    },
    returnId(id, row) {
      const that = this;
      that.formData.repairId = id;
      that.selectCoupCard = row;
      that.cardSelectShow = false;
    },
    /**
     * 确认新建
     */
    submitForm: _debounce(function(formName, flag) {
      const that = this;
      if (!that.formData.cardTemplateJson) {
        return false;
      }
      let tag = true;
      that.formData.cardTemplateJson.forEach(ele => {
        if (!ele.dateRange) {
          ele.dateRange = [];
          tag = false;
        }
        ele.startTimeString = !!ele.dateRange ? ele.dateRange[0] : '';
        ele.endTimeString = !!ele.dateRange ? ele.dateRange[1] : '';
      });
      if (!tag) {
        that.$message.error({
          duration: 1000,
          message: '请先选择模板有效期'
        });
        return false;
      }
      if (!that.formData.cardTemplateJson.length) {
        that.cardErr = true;
        return false;
      } else {
        that.cardErr = false;
      }
      // 选择部门
      if (that.formData.sendRange == 1 && !that.formData.departmentJson.length) {
        that.$message.error({
          duration: 1000,
          message: '请先选择发送的部门'
        });
        return false;
      }
      that.$refs[formName].validate(valid => {
        if (valid) {
          that.postSaveCard(flag);
        }
      });
    }, 300),
    postSaveCard(flag) {
      const that = this;
      let para = {
        repairId: that.formData.repairId,
        cardCombineName: that.formData.cardCombineName,
        cardTemplateJson: JSON.stringify(that.formData.cardTemplateJson),
        sendRange: that.formData.sendRange,
        positionFlag: that.formData.positionFlag ? 1 : 0,
        positionNames: !!that.formData.positionNames.length ? that.formData.positionNames.join(',') : '',
        departmentJson: JSON.stringify(that.formData.departmentJson), // 部门数据
        fixdTimes: that.formData.fixdTimes,
        wxEnterpriseId: that.wxEnterpriseId
      };
      postRequest(that.$route.query.repairId ? '/haoban-app-customer-web/inner/save-repair' : '/haoban-app-customer-web/inner/save-repair', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            showMsg.showmsg(that.$route.query.repairId ? '编辑卡券策略成功' : '新建卡券策略成功', 'success');
            if (!flag) {
              that.$router.push(`/cardPut`);
            } else {
              that.formData = {
                repairId: '',
                cardCombineName: '',
                cardTemplateJson: [],
                sendRange: '0',
                positionFlag: false,
                noPosition: false,
                positionNames: [],
                departmentJson: [],
                fixdType: '0',
                fixdTimes: ''
              };
              that.selectCoupCard = {};
            }
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    /**
     * 改变选择范围
     */
    changeRange(e) {
      const that = this;
      that.formData.selectList = [];
    },
    /**
     * 获取卡券策略数据
     */
    getCardData() {
      const that = this;
      let para = {
        repairId: that.$route.query.repairId
      };
      getRequest('/haoban-app-customer-web/inner/find-repair', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            resData.result.cardTemplateRelateds.forEach(ele => {
              ele.effectiveType = String(ele.effectiveType);
              ele.dateRange = [ele.startTimeString ? ele.startTimeString : '', ele.endTimeString ? ele.endTimeString : ''];
            });
            that.formData = {
              repairId: resData.result.repairId,
              cardCombineName: resData.result.cardCombineName,
              cardTemplateJson: resData.result.cardTemplateRelateds || [],
              sendRange: String(resData.result.sendRange),
              positionFlag: resData.result.positionFlag == 1 ? true : false,
              positionNames: !!resData.result.positionNames.length ? resData.result.positionNames.split(',') : [],
              departmentJson: resData.result.departmentRelateds || [], // 部门数据
              fixdType: '0',
              fixdTimes: resData.result.fixdTimes
            };
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {
    brandId: function(newData, oldData) {
      const that = this;
      if (!!newData && that.$route.query.repairId) {
        that.activeBrand = newData;
        that.getCardData();
      }
    },
    activeGroupId: function(newData, oldData) {
      const that = this;
      if (!!newData) {
        that.activeGroup = newData;
      }
    }
  },
  mounted() {
    const that = this;
    that.$emit('showTab', '3');
    that.$nextTick(() => {
      that.handleDay();
    });

    if (that.$route.query.repairId) {
      that.getCardData();
    }
  }
};
</script>
<style type="text/less" lang="less" scoped>
.card-add-btn {
  width: 143px;
  height: 32px;
  border: 1px solid rgba(192, 196, 204, 1);
}
.cursor-not-allowed {
  cursor: not-allowed;
  background-color: #f5f7fa;
  border-color: #c4c6cf;
  color: #c0c4cc;
}
.selected-card {
  height: 32px;
  line-height: 32px;
  text-align: center;
  padding: 0 15px;
  background: rgba(245, 247, 250, 1);
  border-radius: 2px;
}
.new-card-body {
  padding: 30px;
}
.position-select {
  width: 370px;
  margin-top: 10px;
  padding: 15px 20px;
  min-height: 94px;
  background: rgba(245, 247, 250, 1);
}
.month-recyle {
  width: 370px;
  background: rgba(245, 247, 250, 1);
  padding: 20px;
}
.date-valid {
  width: 400px;
  background: rgba(245, 247, 250, 1);
  padding: 20px;
}
.w-240 {
  width: 240px;
}
.w-90 {
  width: 90px;
}
.w-100 {
  width: 100px;
}
.w-300 {
  width: 300px;
}
.m-l-40 {
  margin-left: 40px;
}
.m-r-8 {
  margin-right: 8px;
}
.item-title {
  margin-bottom: 15px;
}
.depart-item-content {
  width: 213px;
  height: 32px;
  overflow: hidden;
  white-space: nowrap;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  cursor: pointer;
  .el-select__tags {
    overflow: hidden;
    white-space: nowrap;
  }
}

.el-form-item.is-error {
  /deep/ .el-input__inner {
    border-color: #dcdfe6;
    &:focus {
      border-color: #dcdfe6;
    }
  }
}

.w-103 {
  width: 103px;
}
.w-369 {
  width: 369px;
}
.el-input {
  /deep/ .el-input-group__prepend {
    background-color: #fff;
  }
}

.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 22px;
  line-height: 20px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  min-width: 90px;
  max-width: 300px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
