<!--
 * @Descripttion: 完善日指标
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-11-12 10:47:17
 * @LastEditors: 无尘
 * @LastEditTime: 2020-11-30 11:06:29
-->
<template>
  <div class="common-app-right" style="padding: 20px 0;color: #303133">
    <el-form :model="form" label-width="110px">
      <el-form-item label="门店名称">
        <span v-if="form.storeName < 31">{{ form.storeName || '--' }}</span>
        <el-tooltip v-else placement="top">
          <div slot="content">{{ form.storeName || '--' }}</div>
          <span class="hide-ellipsis">{{ form.storeName || '--' }}</span>
        </el-tooltip>
      </el-form-item>
      <el-form-item v-if="!form.multOpt" label="指标额">
        ￥ {{ parseFloat(form.performanceValue || 0).toFixed(2) }}
        <el-button :disabled="disableSetting" type="text" @click="modMonthTarget">修改</el-button>
      </el-form-item>
      <el-form-item label="指标类型">{{ [ '业绩指标日权重', '业绩指标日指标' ][form.performanceSubType - 1] }}</el-form-item>
      <el-form-item v-if="!form.multOpt" label="">
        <div class="content-data">
          <span class="color2">月指标：¥ </span>
          <span class="color1">{{ parseFloat(form.performanceValue || 0).toFixed(2) }}</span>
          <span class="color2">日指标总和：¥  </span>
          <span class="color1" :style="{ color: totalDayTarget != form.performanceValue ? '#F5222D' : '#606266' }">{{ parseFloat(totalDayTarget).toFixed(2) }}</span>
        </div>
      </el-form-item>
    </el-form>

    <div class="target-title">
      <span>{{ form.date[0] }}年{{ form.date[1] }}月</span>
      <!-- 权重编辑时显示 -->
      <el-button v-if="form.flag == true && form.performanceSubType == 1"  type="text" @click="setDefault" :disabled="disableSetting">设置默认日权重</el-button>
    </div>

    <div class="target-table">
      <ul class="table-title">
        <li>周日</li>
        <li>周一</li>
        <li>周二</li>
        <li>周三</li>
        <li>周四</li>
        <li>周五</li>
        <li>周六</li>
      </ul>
      <ul class="table-content">
        <!-- 补充空白 -->
        <li v-for="(item, i) in zerofill" :key="i"></li>

        <li v-for="(item, i) in tableData" :key="i">
          <div>{{ item.performanceDay }}</div>
          <el-input-number v-model="item.performanceValue" :disabled="disableSetting" :precision="2" :controls="false" :max="99999999" style="width: 80px;margin-left:40px;margin-top:5px"></el-input-number>
        </li>

        <!-- 补充空白 -->
        <li v-for="(item, i) in zerofillLast" :key="i"></li>
      </ul>
    </div>

    <el-button type="primary" :loading="loading" :disabled="$route.query.performanceSubType == 2 && totalDayTarget != form.performanceValue || disableSetting" style="margin-left:20px" @click="confirm">保存</el-button>

    <el-dialog
      title="修改指标"
      :visible.sync="dialogVisible"
      width="600px"
      @close="dialogClose">
      <el-alert
        title="修改当月指标会导致已完善的日指标重新下发，并完善。请谨慎设置"
        type="danger"
        show-icon
        :closable="false">
      </el-alert>

      <el-form :model="targetForm" ref="targetForm" hide-required-asterisk label-width="175px" @submit.native.prevent>
        <el-form-item
          prop="value"
          :rules="[
            { required: true, message: '请输入月指标额', trigger: 'blur' }
          ]">
          <span slot="label">
            <span class="color1" style="padding-right:35px">{{ form.performanceYm || '--' }}</span>
            指标额
          </span>

          <el-input v-model="targetForm.value" maxlength="11" style="width: 289px" @blur="value => inputPerformance(value)">
            <span slot="prefix" style="color:#303133;padding-left:5px">￥</span>
          </el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="loadMonth" @click="confirmMonthTarget">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
// import errMsg from '@/common/js/error';
// import showMsg from '@/common/js/showmsg';
import { checkDisEdit } from '@/common/js/public';
import fetch from '@/api/target-manage-app.js';
const { changeStorePerformanceDay, getStorePerformanceDay, changeStorePerformanceMonth } = fetch;
export default {
  name: 'PerfectDayTarget',
  components: {},
  props: {
    brandId: {
      type: String,
      default() {
        return '';
      }
    }
  },
  data() {
    return {
      form: {
        tab: '',
        performanceYm: '',
        performanceSubType: 1, // 1，日权重，2，指标额
        performanceType: 0, // 指标类型，1业绩，2新增会员
        storeInfoId: '',
        storeName: '',
        performanceValue: 0,
        flag: false, // true: 查看， false: 首次完善
        multOpt: '', // 1:批量，
        date: [ '', '' ]
      },
      loading: false,
      days: 0,

      tableData: [],
      zerofill: [],
      zerofillLast: [],

      loadMonth: false,
      targetForm: {
        value: ''
      },
      dialogVisible: false,
      haoban: {},

      disableSetting: false // 是否禁用设置（false：不禁用设置，true：禁用设置）
    };
  },
  mounted() {
    const that = this;
    that.form = JSON.parse(JSON.stringify(that.$route.query));
    that.form.performanceValue = that.form.performanceValue || 0;
    // 批量操作判断
    if (!!that.$route.query.multOpt && that.$route.query.multOpt == 1) {
      that.form.multOpt = 1;
    }else {
      that.form.multOpt = '';
    }
    // 禁用判断
    that.disableSetting = checkDisEdit(that.$route.query.performanceYm);
    const { staffName, staffId, wxEnterpriseId } = JSON.parse(localStorage.getItem('haoBanUser'));
    that.haoban = { submitStaffName: staffName, submitStaffId: staffId, wxEnterpriseId };

    // 修改面包屑
    const { tab, applicationId, performanceYm, flag } = that.$route.query;
    let bread = [ { name: '指标管理', path: '/target-list' }, { name: '查看门店', path: '/target-store' }, { name: flag == false ? '完善日指标' : '查看日指标' } ];
    that.form.date = performanceYm.split('-');
    bread[0].path += `?applicationId=${applicationId}&tab=${tab}`;
    bread[1].path += `?applicationId=${applicationId}&tab=${tab}&performanceYm=${performanceYm}`;
    that.$emit('change-nav', bread);
    that.$emit('showTab', '/target-list');
    that.init();

  },
  beforeDestroy() {
    this.$store.dispatch('clearStoreData');
  },
  methods: {
    /**
     * @description:输入
     * @param {Function} val
     * @author: 无尘
     */
    inputPerformance: function(val) {
      const that = this;
      that.targetForm.value = !!Number(that.targetForm.value.replace(/[^\d.]/g, '')) ? that.targetForm.value.replace(/[^\d+(.\d+)]/g, '') : '';
      that.targetForm.value = Number(that.targetForm.value).toFixed(2) > 99999999.99 ? 99999999.99 : Number(that.targetForm.value).toFixed(2);
    },
    // 修改月指标
    modMonthTarget() {
      const that = this;
      that.targetForm.value = parseFloat(that.form.performanceValue).toFixed(2);
      that.dialogVisible = true;
    },

    // 初始化表格
    init() {
      const that = this;
      if (that.$store.state.storeInfo.length) {
        that.form.storeName = JSON.parse(JSON.stringify(that.$store.state.storeInfo)).map(ele=>ele.storeName).join(',');
        that.form.storeInfoIds = JSON.parse(JSON.stringify(that.$store.state.storeInfo)).map(ele=>ele.storeInfoId).join(',');
        delete that.form.storeInfoId;
      }
      let { date, flag, performanceType, performanceYm, performanceSubType, storeInfoId } = that.form;
      date = date && date.length ? date : [ 2020, 1 ];
      let week = new Date(date[0], date[1] - 1).getDay(); // 第一天周几
      let days = that.days = new Date(date[0], date[1], 0).getDate(); // 一个月天数
      that.zerofill = new Array(week).fill(null); // 补空白
      that.tableData = new Array(days).fill(null).map((item, i) => {
        return {
          performanceDay: i + 1,
          performanceValue: 1
        };
      });
      // 末尾补空白
      let len = (that.zerofill.length + that.tableData.length) % 7;
      if (len) that.zerofillLast = new Array(7 - len).fill(null);

      // 默认值
      if (flag == false) {
        that.setDefault();
      } else if (flag == true) {
        let par = {
          enterpriseId: that.brandId,
          performanceType,
          performanceYm,
          performanceSubType,
          storeInfoId
        };
        getStorePerformanceDay(par, { headers: { sign: that.brandId } })
          .then(res => {
            if (!!res.result && !!res.result.length) {
              res.result.forEach(ele => {
                ele.performanceDay = ele.performanceDay.split('-')[2];
              });
              res.result.sort(function(a, b) {
                return a.performanceDay.replaceAll('-', '') - b.performanceDay.replaceAll('-', '');
              });
              that.tableData = res.result;
            }
          });
      }
    },
    // 修改月指标
    confirmMonthTarget() {
      const that = this;
      that.loadMonth = true;
      that.$refs.targetForm.validate(valid => {
        if (!valid) {
          that.loadMonth = false;
          return;
        }

        const { performanceYm, performanceType, storeInfoId } = that.form;
        let params = {
          ...that.haoban,
          performanceYm,
          performanceType,
          storeInfoId,
          performanceValue: that.targetForm.value
        };
        changeStorePerformanceMonth(params, { headers: { sign: that.brandId } })
          .then(res => {
            // 重新设置指标额
            that.loadMonth = false;
            that.$message.success('修改成功');
            that.form.performanceValue = params.performanceValue;
            that.dialogVisible = false;
            // 日权重时，日指标总和 = 月指标
            if (that.$route.query.performanceSubType == 1) {
              that.totalDayTarget = that.form.performanceValue;
            }
          })
          .finally(() => {
            that.dialogVisible = false;
            that.loadMonth = false;
          });
      });
    },
    // 修改日指标
    confirm() {
      const that = this;
      let flagTip = true;
      that.tableData.forEach(ele => {
        if (!ele.performanceValue || ele.performanceValue <= 0 || !Number(ele.performanceValue)) {
          flagTip = false;
        }
      });
      if (!flagTip) {
        that.$message.error(`每日的${that.$route.query.performanceSubType == 1 ? '权重' : '指标'}不能为空`);
        return false;
      }
      that.loading = true;
      let params = {
        ...that.haoban,
        ...that.form,
        enterpriseId: that.brandId,
        dataJson: that.filterJson()
      };
      changeStorePerformanceDay(params, { headers: { sign: that.brandId } })
        .then(res => {
          that.$message.success('保存成功');
          that.$store.dispatch('clearStoreData');
          that.$router.go(-1);
        })
        .finally(() => that.loading = false);
    },
    dialogClose() {
      this.$refs.targetForm.resetFields();
    },

    // 格式化json数据
    filterJson() {
      return JSON.stringify(this.tableData.map(item => {
        const { performanceDay, performanceValue } = item;
        return {
          performanceValue,
          performanceSubType: this.form.performanceSubType,
          performanceDay: `${this.form.performanceYm}-${performanceDay.toString().padStart(2, '0')}`
        };
      }));
    },
    // 设置默认值 1.00
    setDefault() {
      // let defaultV = (this.form.performanceValue / this.days).toString().match(/^\d+(?:\.\d{0,2})?/)[0];
      this.tableData.forEach(item => item.performanceValue = Number(1).toFixed(2));
    }
  },
  computed: {
    totalDayTarget() {
      if (this.$route.query.performanceSubType == 1) {
        return this.form.performanceValue;
      }
      return this.tableData.reduce((preV, { performanceValue }) => {
        return preV + (performanceValue || 0);
      }, 0);
    }
  },
  watch: {
    brandId(newData) {
      this.init();
    }
  },
};
</script>
<style type="text/less" lang="less" scoped>
.color1 {
  font-size: 16px;
  padding-right: 15px;
  font-weight: 600;
}

.hide-ellipsis {
  max-width: 380px;
  display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
}
.content-data {
  position: relative;
  .color2 {
    position: relative;
    font-size: 14px;
    font-weight: 400;
    &:not(:first-of-type) {
      padding-left: 16px;
      &::before {
        content: '|';
        position: absolute;
        left: 0;
        color: #DCDFE6;
      }
    }
  }
}
.target-title {
  display: flex;
  justify-content: space-between;
  max-width: 100%;
  margin: 20px;
  span {
    font-weight: 600;
  }
}
.target-table {
  max-width: 100%;
  margin: 0 20px 50px;
}
.table-title {
  display: flex;

  li {
    width: 14.28%;
    max-width: 14.28%;
    min-width: 14.28%;
    height: 48px;
    line-height: 48px;
    text-indent: 35px;
    font-weight: 500;
    background-color: #ebecf0;
    // border-bottom: 1px solid #DCDFE6;
    &:not(:last-of-type) {
      border-right: 1px solid #DCDFE6;
    }
  }
}
.table-content {
  display: flex;
  flex-wrap: wrap;
  li {
    width: 14.28%;
    max-width: 14.28%;
    min-width: 14.28%;
    height: 70px;
    padding: 5px 0 8px 10px;
    border-bottom: 1px solid #DCDFE6;
    &:not(:nth-of-type(7n)) {
      border-right: 1px solid #DCDFE6;
    }
  }
}
.el-input-number /deep/.el-input__inner {
  text-align: left;
  border: none;
  background-color: #F5F7FA;
}
.el-form-item {
  margin-bottom: 10px;
}
/deep/.el-alert--danger {
  width: 456px;
  margin-bottom: 20px;
  background: #FFFBE6;
  border-radius: 2px;
  border: 1px solid #FFE58F;
  .el-alert__icon {
    color: #FAAD14;
  }
}
</style>
