<template>
  <!-- 线表计划查询 -->
  <div class="container-chart">
    <el-header style="width: 100%">
      <el-form ref="requestForm" :model="request" label-width="45px">
        <el-row>
          <el-col :span="4">
            <el-form-item label="船号:">
              <el-select v-model="request.dcCh" placeholder="船号" clearable>
                <el-option
                  v-for="item in ShipNoList"
                  :key="item.cbbm"
                  :label="item.cbbm"
                  :value="item.cbbm"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="状态:">
              <el-select v-model="request.Zt" placeholder="状态" clearable>
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="年份:">
              <div style="display: flex">
                <el-date-picker
                  v-model="nrStart"
                  type="year"
                  value-format="yyyy"
                  placeholder=""
                >
                </el-date-picker>
                <div class="distance">~</div>
                <el-date-picker
                  v-model="nrEnd"
                  type="year"
                  value-format="yyyy"
                  placeholder=""
                >
                </el-date-picker>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="text-align: right">
            <el-button type="primary" @click="initList()">查询</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-header>
    <el-container>
      <el-main>
        <vxe-table
          class="mytable-style"
          border
          resizable
          show-footer
          ref="tableRef"
          :max-height="height"
          :header-cell-class-name="headerCellClassName"
          :cell-class-name="cellClassName"
          :footer-method="footerMethod"
          :footer-cell-class-name="footerCellClassName"
          :data="arrList"
          @checkbox-all="selectAllEvent"
          @checkbox-change="selectChangeEvent"
        >
          <vxe-column type="seq" width="80" :resizable="false" show-overflow>
            <template #header>
              <div class="first-col">
                <div class="first-col-top">年份</div>
                <div class="first-col-bottom">产品</div>
              </div>
            </template>
            <template #default="{ row, rowIndex }">
              {{ leftColumn[rowIndex].column }}
            </template>
          </vxe-column>
          <vxe-colgroup
            v-for="(item, index) in topColumn"
            :key="index"
            :title="item.year"
          >
            <vxe-column
              v-for="(em, eindex) in item.months"
              :key="eindex"
              :field="em.field"
              :title="em.title !== '合计' ? em.title + '月' : em.title"
              :width="70"
            >
            </vxe-column>
          </vxe-colgroup>
        </vxe-table>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { getList, tj, save, upload } from "@/api/jhzx/xbjhWH";
import { getCzxx } from "@/api/jhzx/qfxq";
export default {
  name: "xbjhWH",
  data() {
    return {
      request: {
        dcCh: "",
        Zt: "",
        nf: "",
      },
      nrStart: "",
      nrEnd: "",
      height: "500px",
      tableData: [],
      fileList: [],
      checkedList: {},
      statusOptions: [
        {
          value: "0",
          label: "编辑",
        },
        {
          value: "1",
          label: "提交",
        },
        {
          value: "2",
          label: "审核",
        },
      ],
      ShipNoList: [], //船号
      leftColumn: [], //存放左侧列
      topColumn: [], //存放顶部列
      arrList: [], //存放data
      indexes: [],
    };
  },
  created() {
    window.addEventListener("resize", this.getHeight);
    this.initList(); //获取数据
    this.getCzxx();
    this.getHeight();
  },
  methods: {
    // 格式转换
    getTableList(data) {
      this.tableData = data;
      this.leftColumn = []; //左侧列数据
      this.topColumn = []; //顶部列数据
      this.arrList = []; //data数据
      var objeckList = {};
      var sumArr = [];
      var yearArr = [];
      Object.keys(this.tableData).forEach((item, index) => {
        objeckList[item] = {};
        sumArr[item] = [];
        this.indexes[index] = item;
        // 获取左侧列
        this.leftColumn.push({
          column: item,
        });
        this.tableData[item].forEach((em, eindex) => {
          //  获取顶部列
          let yearIndex = yearArr.findIndex((yearEm) => {
            if (yearEm instanceof Object) {
              return yearEm.year == em.nf;
            }
          });

          if (yearIndex == -1) {
            yearArr.push({
              year: em.nf,
              months: [
                {
                  title: em.yf,
                  field: "cl" + em.nf + em.yf,
                  zl: em.zl,
                },
              ],
            });
          } else {
            let monthIndex = yearArr[yearIndex].months.findIndex((monthEm) => {
              if (monthEm instanceof Object) {
                return monthEm.title == em.yf;
              }
            });
            if (monthIndex == -1) {
              yearArr[yearIndex].months.push({
                title: em.yf,
                field: "cl" + em.nf + em.yf,
                zl: em.zl,
              });
            }
          }
        });
      });
      yearArr.forEach((item, index) => {
        item.months.push({
          title: "合计",
          field: "cltotal" + item.year,
        });
      });
      this.topColumn = yearArr; //顶部数据
      // 获取和
      for (let i in this.tableData) {
        for (let v in this.tableData[i]) {
          if (sumArr[i][this.tableData[i][v].nf] >= 0) {
            sumArr[i][this.tableData[i][v].nf] += this.tableData[i][v].zl;
          } else {
            sumArr[i][this.tableData[i][v].nf] = this.tableData[i][v].zl;
          }
        }
      }

      // 获取data数据
      for (let i in this.tableData) {
        for (let v in this.tableData[i]) {
          objeckList[i][
            "cl" + this.tableData[i][v].nf + this.tableData[i][v].yf
          ] = this.tableData[i][v].zl;
          objeckList[i]["cltotal" + this.tableData[i][v].nf] =
            sumArr[i][this.tableData[i][v].nf];
        }
      }
      this.arrList = Object.values(objeckList); //data数据
    },

    // 上传excel
    actionUpload(file) {
      const formData = new FormData();
      formData.append("file", file.file);
      upload(formData).then((res) => {
        if (res.success) {
          this.checkedList = {};
          this.getTableList(res.data);
          this.$message.success("导入成功！");
        }
      });
    },
    // 全选
    selectAllEvent({ checked }) {
      // const records = this.$refs.tableRef.getCheckboxRecords();
      // this.checkedList = records;
      if (checked) {
        this.checkedList = JSON.parse(JSON.stringify(this.tableData));
      } else {
        this.checkedList = {};
      }
    },
    // 单选
    selectChangeEvent({ checked, row, rowIndex }) {
      // const records = this.$refs.tableRef.getCheckboxRecords();
      // this.checkedList = records;
      if (checked) {
        this.checkedList[this.indexes[rowIndex]] =
          this.tableData[this.indexes[rowIndex]];
      } else {
        delete this.checkedList[this.indexes[rowIndex]];
      }
    },
    // 获取船号接口
    getCzxx() {
      getCzxx().then((res) => {
        if (res.success) {
          this.ShipNoList = res.data;
        }
      });
    },
    // 获取列表接口
    initList() {
      let params = {
        dcCh: this.request.dcCh,
        Zt: this.request.Zt,
        nf: "",
      };
      if (this.nrStart && this.nrEnd) {
        params.nf = this.nrStart + "~" + this.nrEnd;
      } else if (
        (this.nrStart && !this.nrEnd) ||
        (!this.nrStart && this.nrEnd)
      ) {
        this.$message.warning("请选择年份范围");
        return;
      } else {
        this.request.nf = "";
      }
      // if()
      getList(params).then((res) => {
        if (res.success) {
          this.checkedList = {};
          this.getTableList(res.data);
        }
      });
    },
    // 表尾列求和
    total(list, field) {
      let count = 0;
      list.forEach((item) => {
        if (item !== "dcCh" && item !== "zt") {
          count += Number(item[field]);
        }
      });
      return count;
    },
    footerMethod({ columns, data }) {
      const totalList = []; //合计
      columns.forEach((column) => {
        if (["checkbox"].includes(column.property)) {
          return "合并了";
        }
        var totalData = null;
        totalData = this.total(data, column.property);
        totalList.push(totalData);
      });
      totalList[0] = "合计";
      return [totalList];
    },
    // 头部header css
    headerCellClassName({ column, $rowIndex }) {
      if ($rowIndex == 0) {
        return "row-gre-header";
      } else {
        if (column.field === "total1" || column.field === "total2") {
          return "row-gre-total-header";
        } else {
          return "row-gre-header";
        }
      }
    },
    // 指定列css
    cellClassName({ column }) {
      if (column.field === "total1" || column.field === "total2") {
        return "col-gre-total-col";
      } else {
        return "col-gre-col";
      }
    },
    // 尾部合计css
    footerCellClassName({ $rowIndex }) {
      if ($rowIndex === 0) {
        return "row-end-gre";
      }
    },
    // 操作
    async toolbarButtonClickEvent(code) {
      switch (code) {
        case "submit":
          if (!JSON.stringify(this.checkedList) =="{}") {
            this.$confirm("是否确认提交选择的数据?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                tj(this.checkedList).then((res) => {
                  if (res.success) {
                    const xTable = this.$refs.tableRef;
                    xTable.loadData(this.initList());
                    this.$message.success("提交成功！");
                  }
                });
              })
              .catch(() => {});
          } else {
            this.$message.warning("请选择数据！");
          }
          break;
        case "save":
          if (JSON.stringify(this.checkedList) =="{}") {
            this.$confirm("是否确认保存选择的数据?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                save(this.checkedList).then((res) => {
                  if (res.success) {
                    const xTable = this.$refs.tableRef;
                    xTable.loadData(this.initList());
                    this.$message.success("保存成功！");
                  }
                });
              })
              .catch(() => {});
          } else {
            this.$message.warning("请选择数据！");
          }
          break;
        default:
          break;
      }
    },
    getHeight() {
      this.height = window.innerHeight - 160;
    },
  },
};
</script>

<style scoped>
.first-col {
  position: relative;
  height: 20px;
}
.first-col:before {
  content: "";
  position: absolute;
  left: -18px !important;
  top: 9px !important;
  width: 95px;
  height: 1px;
  -webkit-transform: rotate(37deg);
  transform: rotate(34deg);
  background-color: #000;
}
.first-col .first-col-top {
  position: absolute;
  right: 4px;
  top: -10px;
}
.first-col .first-col-bottom {
  position: absolute;
  left: 4px;
  bottom: -10px;
}
.my-filter {
  margin: 10px;
}
.page-left {
  position: absolute;
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
  z-index: 10;
}
::v-deep .vxe-table--render-default .vxe-cell {
  text-align: center !important;
}
/* 尾部 */
::v-deep.mytable-style .row-end-gre {
  background-color: #9ed3a4;
  color: #000;
  font-weight: bold;
}
/* 列 */
::v-deep.mytable-style.vxe-table .vxe-body--column.col-gre-total-col {
  background-color: #9ed3a4;
  color: #000;
}
::v-deep.mytable-style.vxe-table .vxe-body--column.col-gre-col {
  background-color: #cce8cf;
  color: #000;
}
/* header */
::v-deep.mytable-style.vxe-table .vxe-header--column.row-gre-header {
  background-color: #cce8cf;
  color: #000;
  font-weight: bold;
}
::v-deep.mytable-style.vxe-table .vxe-header--column.row-gre-total-header {
  background-color: #9ed3a4;
  color: #000;
  font-weight: bold;
}
/* header下边框 */
::v-deep.mytable-style.vxe-table
  .vxe-table--header-wrapper
  .vxe-table--header-border-line {
  border-bottom: 2px solid #000 !important;
}
/* border 颜色 */
::v-deep .vxe-table--render-default.border--full .vxe-body--column,
.vxe-table--render-default.border--full .vxe-footer--column,
.vxe-table--render-default.border--full .vxe-header--column {
  background-image: linear-gradient(#000, #000) !important;
}
::v-deep.vxe-table--render-default.border--full .vxe-body--column,
.vxe-table--render-default.border--full .vxe-footer--column,
.vxe-table--render-default.border--full .vxe-header--column {
  background-image: linear-gradient(#000, #000), linear-gradient(#000, #000) !important;
}
:v-deep.vxe-table--render-default.border--full .vxe-body--column,
.vxe-table--render-default.border--full .vxe-footer--column,
.vxe-table--render-default.border--full .vxe-header--column {
  background-image: linear-gradient(#000, #000), linear-gradient(#000, #000) !important;
}
::v-deep.vxe-table--render-default.border--full .vxe-body--column,
::v-deep.vxe-table--render-default.border--full .vxe-footer--column,
::v-deep.vxe-table--render-default.border--full .vxe-header--column {
  background-image: linear-gradient(#000, #000), linear-gradient(#000, #000) !important;
}
/* 尾部上边框 */
::v-deep.vxe-table--render-default .vxe-table--footer-wrapper {
  border-top: 2px solid #000 !important;
}
::v-deep.vxe-table--render-default .vxe-cell--checkbox .vxe-checkbox--icon {
  color: #000;
  font-weight: 400 !important;
}
.upload-demo {
  display: inline-flex;
  margin-right: 10px;
}
::v-deep .el-upload-list {
  display: none !important;
}
.el-main {
  padding: 0;
}
.el-container {
  padding-top: 5px;
  width: 100%;
  margin: 0;
}
.el-header {
  margin: 0;
  padding: 5px 0;
  height: auto;
}
.el-row {
  margin-bottom: 5px;
}
::v-deep .el-form-item {
  margin-bottom: 0px !important;
}
.distance {
  margin-left: 5px;
  margin-right: 5px;
}
</style>
