<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="船号:">
              <vxe-pulldown ref="xDown4" transfer >
                <template #default>
                  <vxe-input
                    v-model="request.dcCh"
                    placeholder="船号"
                    style="height: 28px;
                    line-height: 28px; width: 150px;"
                    suffix-icon="vxe-icon--search"
                    @keyup="keyupEvent4"
                    @focus="focusEvent4"
                  />
                </template>
                <template #dropdown>
                  <div class="my-dropdown  mytable " style="width: 250px">
                    <vxe-grid
                      highlight-hover-row
                      height="300px"

                      :data="projectData"
                      :columns="projectColumns"
                      @cell-click="cellClickEvent"
                      show-overflow
                    >
                      <template #wgbsEdit="{ row}">
                        <vxe-checkbox v-model="row.wgbs"  checked-value="Y" unchecked-value="N"   disabled ></vxe-checkbox>
                      </template>
                    </vxe-grid>
                  </div>
                </template>
              </vxe-pulldown>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="年份:" style="width: 260px;">
              <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="16" 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"
        >
          <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";
import XEUtils from "xe-utils";
import {getCzplBase} from "@/api/sjzx/jcsj";
export default {
  name: "xbjhCX",
  data() {
    return {
      request: {
        dcCh: "",
        Zt: "",
        nf: "",
      },
      projectData:[],
      projectData1:[],
      projectColumns: [
        {field: 'cbbm', title: '船号',width: 110},
        { field: 'wgbs', title: '完工标识', width: 80,
          slots:{
            default: 'wgbsEdit'
          },
        },
      ],
      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: {
    cellClickEvent({row}) {
      this.request.dcCh = row.cbbm
      this.$refs.xDown4.hidePanel()
    },
    focusEvent4() {
      this.$refs.xDown4.showPanel()
    },
    keyupEvent4() {


      if (this.request.dcCh) {
        this.projectData = this.projectData1.filter(row => row.project.indexOf(this.request.dcCh.toUpperCase()) > -1)
      } else {
        this.projectData = this.projectData1.slice(0)
      }

    },
    // 排序
    compare(property) {
      return function (object1, object2) {
        let value1 = object1[property];
        let value2 = object2[property];
        // 升序
        return value1 - value2;
      };
    },
    // 格式转换
    getTableList(data) {
      Object.keys(data).forEach((item, index) => {
        data[item].sort(this.compare("nf"));
        data[item].sort(this.compare("yf"));
        data[item].forEach((em) => {
          em.zl = em.zl ? em.zl : null;
        });
      });

      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
          ]
            ? 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;
        }
      });
      getCzplBase({}).then(res=>{
        this.projectData=res.data.cbbm
        this.projectData1=res.data.cbbm
      })
    },
    // 获取列表接口
    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 = "";
      }
      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 }) {
      console.log( columns, data)
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 0) {
            return '合计'
          }
          return this.sumNum(data, column.property)
        })
      ]
    },
    sumNum(list, field) {
      let count = 0
      list.forEach(item => {
        let num = Number(item[field])
        if (!XEUtils.isNumber(num) || isNaN(num)) {
          num = 0
        }
        count = this.cal.accAdd(count, num)
      })
      return count==0?'-':count;
    },
    // 头部header css
    headerCellClassName({ column, $rowIndex }) {
      if ($rowIndex == 0) {
        return "row-gre-header";
      } else {
        if (column.field.indexOf("cltotal") > -1) {
          return "row-gre-total-header";
        } else {
          return "row-gre-header";
        }
      }
    },
    // 指定列css
    cellClassName({ column }) {
      if (column.field) {
        if (column.field.indexOf("cltotal") > -1) {
          return "col-gre-total-col";
        } else {
          return "col-gre-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 lang="scss">
.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{
  background-image: linear-gradient(#000, #000), linear-gradient(#000, #000) !important;
  background-repeat: no-repeat !important;
  background-size: 1px 100%,100% 1px !important;
  background-position: 100% 0px,100% 99% !important;
}
::v-deep.vxe-table--render-default.border--full .vxe-footer--column{
  background-image: linear-gradient(#000, #000), linear-gradient(#000, #000) !important;
}
::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>
