<!--
 * @Descripttion: 完善日指标
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-11-12 10:47:17
 * @LastEditors: 无尘
 * @LastEditTime: 2020-11-23 18:23:16
-->
<template>
  <div class="common-app-right" style="padding: 20px 0;color: #303133">
    <el-form :model="form" label-width="110px">
      <el-form-item label="门店名称">{{ form.storeName || '--' }}</el-form-item>
      <el-form-item label="指标额">
        ￥ {{ parseFloat(form.performanceValue).toFixed(2) }}
        <el-button type="text" @click="modMonthTarget">修改</el-button>
      </el-form-item>
      <el-form-item label="指标类型">{{ [ '业绩指标日权重', '业绩指标日指标' ][form.performanceSubType - 1] }}</el-form-item>
      <el-form-item label="">
        <div class="content-data">
          <span class="color2">月指标：¥ </span>
          <span class="color1">{{ parseFloat(form.performanceValue).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 type="text" @click="setDefault" v-if="form.flag == false && form.performanceSubType == 1">设置默认日权重</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" :precision="2" :controls="false" 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" 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" style="width: 289px">
            <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 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: 首次完善
        date: [ '', '' ]
      },
      loading: false,
      days: 0,

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

      loadMonth: false,
      targetForm: {
        value: ''
      },
      dialogVisible: false,
      haoban: {}
    };
  },
  created() {
    this.form = JSON.parse(JSON.stringify(this.$route.query));
    const { staffName, staffId, wxEnterpriseId } = JSON.parse(localStorage.getItem('haoBanUser'));
    this.haoban = { staffName, staffId, wxEnterpriseId };

    let bread = [ { name: '指标管理', path: '/target-list' }, { name: '查看门店', path: '/target-store' }, { name: '完善日指标' } ];
    // 修改面包屑
    const { tab, applicationId, performanceYm } = this.$route.query;
    this.form.date = performanceYm.split('-');
    bread[0].path += `?applicationId=${applicationId}&tab=${tab}`;
    bread[1].path += `?applicationId=${applicationId}&tab=${tab}&performanceYm=${performanceYm}`;
    this.$emit('change-nav', bread);
    this.init();
  },
  mounted() {
    this.$emit('showTab', '/target-list');
  },
  // watch: {
  //   brandId() {
  //   }
  // },
  methods: {
    // 修改月指标
    modMonthTarget() {
      const that = this;
      that.targetForm.value = parseFloat(that.form.performanceValue).toFixed(2);
      that.dialogVisible = true;
    },

    // 初始化表格
    init() {
      const that = this;
      let { date, flag, performanceType, performanceYm, performanceSubType, storeInfoId } = this.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.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.$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);
    }
  },
};
</script>
<style type="text/less" lang="less" scoped>
.color1 {
  font-size: 16px;
  padding-right: 15px;
  font-weight: 600;
}
.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;
  width: 1145px;
  margin: 20px;
  span {
    font-weight: 600;
  }
}
.target-table {
  width: 97%;
  margin: 0 20px 50px;
}
.table-title {
  display: flex;

  li {
    width: 14%;
    max-width: 14%;
    min-width: 14%;
    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%;
    max-width: 14%;
    min-width: 14%;
    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>
