<template>
  <div class="testdiv">
    <!-- 查询条件 -->
    <div class="divborder newSearchDiv" style="margin: 0px">
      <!-- 产线层级 -->
      <div class="filter">
        <label>产线层级：</label>
        <Cascader
          :data="levelData"
          :value="curLevel"
          trigger="click"
          change-on-select
          class="searchSelect"
          @on-change="cascaderChange"
        ></Cascader>
      </div>
      <!-- 日期范围 -->
      <div class="filter">
        <label>日期范围：</label>
        <DatePicker
          type="month"
          :value="month"
          class="searchInput"
          @on-change="monthChange"
        ></DatePicker>
      </div>
      <!-- 统计维度 -->
      <div class="filter">
        <label>统计维度：</label>
        <Select
          v-model="base"
          label-in-value
          class="searchSelect"
          @on-change="baseChange"
        >
          <Option :value="1">工位</Option>
          <Option :value="2">人员</Option>
        </Select>
      </div>
      <!-- 按钮组 -->
      <div class="searchBtn">
        <!-- 查询按钮 -->
        <Button
          type="primary"
          class="twoWord"
          icon="ios-search-outline"
          @click="search()"
          >{{ $t(1001) }}</Button
        >
        <!-- 导出按钮 -->
        <Button
          type="primary"
          class="fourWord"
          icon="ios-download-outline"
          @click="output()"
          >{{ $t(1007) }}</Button
        >
        <!-- 设置标准值按钮 -->
        <Button
          type="primary"
          class="fourWord"
          icon="ios-build-outline"
          @click="setStandard()"
          >标准值设置</Button
        >
      </div>
    </div>
    <div class="divborder newTableDiv">
      <!-- 主体表格 -->
      <Table
        id="qualityReportTable"
        class="tableClass"
        :data="tableData"
        :columns="tableColumns"
      ></Table>
    </div>
    <!-- 标准值设置弹框 -->
    <Modal
      class="newModalClass qualityReportModal"
      v-model="standardModal"
      :styles="{ width: '520px' }"
    >
      <p slot="header">
        <span>合格率标准值设置</span>
      </p>
      <div class="modal_body">
        <div class="standardModal">
          <div class="standard_color">
            <h4>指标颜色</h4>
            <div class="success"></div>
            <div class="warn"></div>
            <div class="error"></div>
          </div>
          <div class="standard_section">
            <h4>合格率区间</h4>
            <div>
              <InputNumber
                v-model="successMin"
                :min="0"
                :max="100"
                class="searchInput"
              />
              <span>&nbsp;&nbsp;~&nbsp;&nbsp;</span>
              <InputNumber
                v-model="successMax"
                :min="0"
                :max="100"
                class="searchInput"
              />
            </div>
            <div>
              <InputNumber
                v-model="warnMin"
                :min="0"
                :max="100"
                class="searchInput"
              />
              <span>&nbsp;&nbsp;~&nbsp;&nbsp;</span>
              <InputNumber
                v-model="warnMax"
                :min="0"
                :max="100"
                class="searchInput"
              />
            </div>
            <div>
              <InputNumber
                v-model="errorMin"
                :min="0"
                :max="100"
                class="searchInput"
              />
              <span>&nbsp;&nbsp;~&nbsp;&nbsp;</span>
              <InputNumber
                v-model="errorMax"
                :min="0"
                :max="100"
                class="searchInput"
              />
            </div>
          </div>
        </div>
      </div>
      <div slot="footer">
        <Button size="large" @click="standardModal = false" v-text="$t('1033')"
          >取消</Button
        >
        <Button type="primary" size="large" @click="saveStandard()"
          >确认</Button
        >
      </div>
    </Modal>
    <!-- 不合格记录详情弹出框 -->
    <Modal
      class="newModalClass progressModal"
      v-model="recordModal"
      :width="999"
    >
      <p slot="header">
        <span>{{ today }}不合格记录详情</span>
      </p>
      <div class="modal_body">
        <div>
          <Table
            :data="recordTableData"
            :columns="recordTableColumns"
            :max-height="520"
          ></Table>
        </div>
      </div>
      <div slot="footer"></div>
    </Modal>
  </div>
</template>

<script>
import moment from "moment";

export default {
  inject: ["reload"],
  data() {
    return {
      //  TODAY
      today: "",
      // 产线层级级联数据
      levelData: [],
      // 搜索条件--产线层级
      curLevel: [],
      // 产线层级深度
      levelNums: 0,
      // 搜索条件--月份
      month: moment(new Date()).format("YYYY-MM"),
      // 搜索条件--统计维度
      base: 1,
      // 当前选中的行数据
      row: {},
      // 主体表格数据
      tableData: [],
      // 主体表格列字段
      tableColumns: [],
      // 不合格区间
      errorSection: localStorage.getItem("errorSection")
        ? JSON.parse(localStorage.getItem("errorSection"))
        : [0, 75],
      // 良好区间
      warnSection: localStorage.getItem("warnSection")
        ? JSON.parse(localStorage.getItem("warnSection"))
        : [75, 85],
      // 优秀区间
      successSection: localStorage.getItem("successSection")
        ? JSON.parse(localStorage.getItem("successSection"))
        : [85, 100],
      // 标准值设置弹框是否显示
      standardModal: false,
      // 标准值设置相关参数
      successMin: 0,
      successMax: 0,
      warnMin: 0,
      warnMax: 0,
      errorMin: 0,
      errorMax: 0,
      // 不合格记录详情弹框是否显示
      recordModal: false,
      // 不合格记录详情弹框中表格数据
      recordTableData: [],
      // 不合格记录详情弹框中表格字段
      recordTableColumns: [
        {
          title: "序号",
          type: "index",
          width: 60,
        },
        {
          title: "产品名称",
          key: "productName",
          align: "center",
        },
        {
          title: "工序",
          key: "procedure",
          align: "center",
        },
        {
          title: "设备位置",
          key: "devicePosition",
          align: "center",
        },
        {
          title: "生产执行人",
          key: "operator",
          align: "center",
        },
        {
          title: "工令号",
          key: "workOrderNo",
          align: "center",
        },
        {
          title: "不合格数",
          key: "noOkNum",
          align: "center",
        },
        {
          title: "报工时间",
          key: "reportTime",
          align: "center",
          width: 150,
        },
      ],
      queryInfo: "", //跳转页面参数
      levelid: 0,
    };
  },
  created() {
    //获取跳转传过来的值
    let queryInfo = JSON.parse(localStorage.getItem("queryInfo"));
    localStorage.removeItem("queryInfo"); //清除缓存数据
    if (queryInfo && queryInfo != undefined) {
      this.queryInfo = queryInfo;
      this.levelid = queryInfo.sectionid;
      this.month = moment(queryInfo.datetime[0]).format("YYYY-MM");
    }
  },
  mounted() {
    // 获取产线层级级联数据
    this.getCascader();
    // 初始化表格字段
    this.recordTableColumns = this.$time.initTableTitle(
      this.recordTableColumns
    );
    this.search();
  },
  methods: {
    // 格式化表格字段
    initTableColumns(arr) {
      const _this = this;

      let { numBetween, errorSection, warnSection, successSection } = this;

      if (Array.isArray(arr) && arr.length) {
        arr.forEach(function (item, index) {
          if (index == 0) {
            item.width = 120;
          } else {
            item.minWidth = 50;
            item.render = (h, params) => {
              let v = params.row[`day${index}`];
              let bgColor, cursor;
              if (numBetween(v, errorSection)) {
                // 不合格区间
                bgColor = "#D9001B";
                cursor = "pointer";
              } else if (numBetween(v, warnSection)) {
                // 良好区间
                bgColor = "#F59A23";
              } else if (numBetween(v, successSection)) {
                // 优秀区间
                bgColor = "#70B603";
              } else {
                // 没捕捉到的区间
                bgColor = "#2D8CF0";
              }
              return h("div", {
                style: {
                  backgroundColor: bgColor,
                  cursor: cursor || "default",
                  color: "#fff",
                  width: "100%",
                  height: "36px",
                  lineHeight: "36px",
                  textAlign: "center",
                },
                domProps: {
                  innerHTML: `${v}%`,
                },
                on: {
                  click: function () {
                    if (numBetween(v, errorSection)) {
                      let day = index > 9 ? `${index}` : `0${index}`;
                      _this.today = `${_this.month}-${day}`;
                      _this.getDetails(params.row.id, _this.today);
                      _this.recordModal = true;
                    }
                  },
                },
              });
            };
          }
          item.align = "center";
        });
      }
      return arr;
    },
    // 判断一个数值是否在某一个区间内
    numBetween(num, arr) {
      if (Array.isArray(arr) && arr.length == 2) {
        if (num > arr[0] && num <= arr[1]) {
          return true;
        }
        return false;
      }
      return false;
    },
    // 选中表格一行数据
    handleRowChange(v) {
      this.row = v;
    },
    // 监听产线层级级联数据变化
    cascaderChange(v) {
      this.curLevel = v;
      this.levelid = v[v.length - 1] ? v[v.length - 1] : 0;
    },
    // 获取产线层级级联数据
    getCascader() {
      const _this = this;
      _this.axios
        .request({
          url: "/config/ProjectLevelSection/GetSectionTree",
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            let data = result.data;
            _this.levelData = data;
            _this.levelNums = _this.getMaxFloor(data);
            _this.curLevel = [data[0].value];
          } else {
            _this.$Message.error(_this.$t("" + result.msg));
          }
        });
    },
    // 根据树形结构数据算出树形结构数据的深度
    getMaxFloor(treeData) {
      let floor = 0;
      let max = 0;
      function each(data, floor) {
        data.forEach((e) => {
          e.floor = floor;
          if (floor > max) {
            max = floor;
          }
          if (e.children.length > 0) {
            each(e.children, floor + 1);
          }
        });
      }
      each(treeData, 1);
      return max;
    },
    // 监听月份变化
    monthChange(v) {
      this.month = v;
    },
    // 监听统计维度变化
    baseChange() {},
    // 获取主体表格数据
    search(isExport) {
      const _this = this;
      let { curLevel, month, base, levelid } = this;
      if (!month) {
        _this.$Message.error(_this.$t(444434));
        return false;
      }
      let params = {
        sectionid: levelid,
        starttime: month,
        endtime: month,
        dimension: base,
        toexcel: isExport ? isExport : 0,
      };
      _this.axios
        .request({
          url: "cnc/PerformanceStatistics/GetQualificationRate",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            if (isExport == 1) {
              location.href = _this.axios.publicPath + result.data;
              return false;
            }
            let data = result.data;
            let xdata = data.xdata;
            let ydata = data.ydata;

            // 处理表格数据
            let tableData = [];
            _this.tableColumns = [];
            if (ydata && Array.isArray(ydata) && ydata.length) {
              // 处理表格列字段
              _this.tableColumns = _this.initTableColumns(xdata);
              ydata.forEach((v, i) => {
                let temp = {};
                temp.base = v.stationperson;
                temp.id = v.stationpersonid;
                v.day.forEach((item) => {
                  temp[item.key] = item.percent;
                });
                tableData.push(temp);
              });
            }
            _this.tableData = tableData;
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        });
    },
    // 数据导出
    output() {
      this.search(1);
    },
    // 标准值设置
    setStandard() {
      // 反绑标准值数据
      this.successMin = this.successSection[0];
      this.successMax = this.successSection[1];
      this.warnMin = this.warnSection[0];
      this.warnMax = this.warnSection[1];
      this.errorMin = this.errorSection[0];
      this.errorMax = this.errorSection[1];
      // 弹框弹出
      this.standardModal = true;
    },
    // 保存标准值设置
    saveStandard() {
      let {
        successMin,
        successMax,
        warnMin,
        warnMax,
        errorMin,
        errorMax,
      } = this;
      this.successSection = [successMin, successMax];
      localStorage.setItem(
        "successSection",
        JSON.stringify(this.successSection)
      );
      this.warnSection = [warnMin, warnMax];
      localStorage.setItem("warnSection", JSON.stringify(this.warnSection));
      this.errorSection = [errorMin, errorMax];
      localStorage.setItem("errorSection", JSON.stringify(this.errorSection));
      this.$Message.success(this.$t(1112));
      this.standardModal = false;
      this.reload();
    },
    // 获取详情
    getDetails(id, today) {
      const _this = this;
      let { curLevel, month, base, levelid } = this;
      let params = {
        sectionid: levelid,
        starttime: today,
        endtime: today,
        dimension: base,
        stationpersonid: id,
      };
      _this.axios
        .request({
          url: "cnc/PerformanceStatistics/GetDataDetail",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            let data = result.data;
            let recordTableData = [];
            if (data && Array.isArray(data) && data.length) {
              data.forEach((v) => {
                recordTableData.push({
                  productName: v.product_name,
                  procedure: v.route_name,
                  devicePosition: v.machinelocal,
                  team: v.name,
                  operator: v.worker_name,
                  workOrderNo: v.code,
                  noOkNum: v.nok_number,
                  reportTime: moment(new Date(v.time * 1000)).format(
                    "YYYY-MM-DD HH:mm:ss"
                  ),
                });
              });
            }
            _this.recordTableData = recordTableData;
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        });
    },
  },
};
</script>
<style lang="less">
#qualityReportTable .ivu-table-cell {
  padding-left: 1px;
  padding-right: 1px;
}

.qualityReportModal .standardModal {
  display: flex;
  align-items: center;

  .standard_color {
    margin-right: 14px;
    width: 100px;
    text-align: center;

    > div {
      height: 29px;
      width: 80%;
      margin: 0 auto;
      margin-top: 14px;
    }
    .success {
      background-color: #70b603;
    }
    .warn {
      background-color: #f59a23;
    }
    .error {
      background-color: #d9001b;
    }
  }

  .standard_section {
    text-align: center;
    > div {
      margin-top: 14px;
    }
  }
}
</style>
