<template>
  <div>
    <!-- 查询配置 -->
    <div>
      <div ref="lxHeader">
        <LxHeader
          icon="md-apps"
          :text="$route.meta.title"
          style="margin-bottom: 10px; border: 0px; margin-top: 15px"
        >
          <div slot="content"></div>
          <slot>
            <header-content :auths="auths_auth_mixin">
              <template #search>
                <div style="display: flex">
                  <el-cascader clearable placeholder="请选择范围" size="small" collapse-tags :value="select.filter[2].value" :options="equipments" :props="{ children: 'children', label: 'name', value: 'id', multiple: true, emitPath: false }" @change="handleCheckChange"></el-cascader>

                  <Select clearable v-model="select.filter[1].value" placeholder="请选择类别" style="width: 140px;margin-left: 6px;">
                    <Option v-for="item in abilities" :value="item.value">{{ item.key }}</Option>
                  </Select>
                  <Input style="width: 140px;margin-left: 6px;" clearable v-model="select.filter[0].value" placeholder="搜索内容"/>
                  <Button
                    style="margin-left: 10px"
                    type="primary"
                    @click="$refs['xyTable'].getTableData(true)"
                  >查询</Button
                  >
                </div>
              </template>
              <template #export>
                <Button
                  type="primary"
                  @click="exportExcel(new Date().getTime().toString())"
                >导出</Button
                >
              </template>
            </header-content>
          </slot>
        </LxHeader>
      </div>
    </div>

    <el-row :gutter="10">
<!--      <el-col :span="4">-->
<!--        <el-tree :data="equipments"-->
<!--                 node-key="id"-->
<!--                 :style="{ 'max-height':  treeHeight, 'overflow': 'scroll' }"-->
<!--                 ref="elTree"-->
<!--                 :props="{ children: 'children', label: 'name' }"-->
<!--                 show-checkbox-->
<!--                 @check="handleCheckChange">-->
<!--        </el-tree>-->
<!--      </el-col>-->
      <el-col :span="24">
        <xy-table
          :btn-width="240"
          :auths="auths_auth_mixin"
          :delay-req="true"
          :destroy-action="destroy"
          ref="xyTable"
          :border="true"
          :action="index"
          :req-opt="tableSelect"
          :destroy-req-opt="select"
          :table-item="table"
          @detail="
        (row) => {
        }
      "
          @editor="
        (row) => {
        }
      "
          @loaded="adjustAlignment"
        >
        </xy-table>
      </el-col>
    </el-row>

  </div>
</template>

<script>
import {index as fieldIndex, show as formFieldShow} from "@/api/system/customFormField";
import { authMixin } from "@/mixin/authMixin";
import { index, destroy, save } from "@/api/system/baseForm";
import { op } from "@/const/op";
import { download } from "@/utils/downloadRequest";
import { getparameter } from "@/api/system/dictionary";
import { show } from "@/api/system/customForm";
import * as XLSX from "xlsx";
import { saveAs } from "file-saver";
import { listdept } from "@/api/system/department";

import LxHeader from "@/components/LxHeader/index.vue";
import headerContent from "@/components/LxHeader/XyContent.vue";
import {deepCopy} from "@/utils";
export default {
  components: {
    LxHeader,
    headerContent,
  },
  mixins: [authMixin],
  provide: {
    formStore: () => this.form,
  },
  data() {
    return {
      firstAdjustTable: true,
      op,
      select: {
        table_name: "",
        sort_name: 'equipment_id',
        filter: [
          {
            key: "content",
            op: "like",
            value: ""
          },
          {
            key: "leibie",
            op: "eq",
            value: ""
          },
          {
            key: "equipment_id",
            op: "in",
            value: []
          },
          {
            key: 'start_time',
            op: 'range',
            value: `${this.$moment().startOf('days').format('YYYY-MM-DD HH:mm:ss')},${this.$moment().endOf('days').format('YYYY-MM-DD HH:mm:ss')}`
          },
          {
            key: 'status',
            op: 'neq',
            value: 1
          }
        ],
      },
      selectQuery: [],
      form: [],
      customForm: {
        customFormId: "",
        tableName: "",
      },

      abilities: [],
      equipments: [],
      diaolingleixing: [],
      table: [
        {
          prop: "id",
          width: 60,
          label: "序号",
          formatter: (row, column, cellValue, index) => (this.$refs['xyTable'].selectOpt.page - 1) * this.$refs['xyTable'].selectOpt.page_size + index + 1
        },
        {
          "prop": "equipment_id_equipments_id_relation.name",
          "label": "点位",
          "width": 160,
          "align": "center"
        },
        {
          "prop": "start_time",
          "label": "开始时间",
          "width": 0,
          "align": "center"
        },
        {
          "prop": "end_time",
          "label": "结束时间",
          "width": 0,
          "align": "center"
        },
        {
          "prop": "kaiqishuliang",
          "label": "闸门开启数量",
          "width": 0,
          "align": "center"
        },
        {
          "prop": "kaiqishuliang1",
          "label": "水泵开启数量",
          "width": 0,
          "align": "center"
        },
        {
          "prop": "leibie",
          "label": "类别",
          "width": 140,
          "align": "center",
          formatter: (data,row,val) => this.abilities.find(i => i.value === val)?.key
        },
        // {
        //   prop: "status",
        //   label: "状态",
        //   align: "center",
        //   width: 420,
        //   customFn: row => (
        //     <div class="list-item__operate">
        //       {
        //         this.progressStatus(row).map((s, si) => (
        //           <el-tooltip effect="dark" content={this.operateTitle(row, s)||'暂无时间'} placement="top">
        //             <div class="step">
        //               <div class="step-icon">
        //                 <div class={`step-icon__cir-${this.stepFormat(row.status, s.value)} step-icon__cir`}></div>
        //                 {
        //                   si < this.progressStatus(row).length - 1 ? (<div
        //                     class={`step-icon__line-${this.stepFormat(row.status, s.value)} step-icon__line`}></div>) : ""
        //                 }
        //               </div>
        //               <div class="step-label">{s.label}</div>
        //             </div>
        //           </el-tooltip>
        //         ))
        //       }
        //     </div>
        //   )
        // },
        {
          "prop": "act_start_time",
          "label": "实际开始时间",
          "width": 0,
          "align": "center"
        },
        {
          "prop": "act_end_time",
          "label": "实际结束时间",
          "width": 0,
          "align": "center"
        },
        {
          "prop": "content",
          "label": "调令内容",
          "width": 0,
          "align": "center"
        },
        {
          "prop": "tiaozhengleixing",
          "label": "调整类型",
          "width": 0,
          "align": "center"
        },

      ],
      status: [
        {
          value: 2,
          label: "接收",
          auth: "receive"
        },
        {
          value: 3,
          label: "通知开启",
          auth: "noticeOpen"
        },
        {
          value: 4,
          label: "开启",
          auth: "open"
        },
        {
          value: 4,
          label: "已开启",
          auth: "open",
        },
        {
          value: 5,
          label: "确认关闭通知",
          auth: "noticeClose"
        },
        {
          value: 6,
          label: "确认关闭",
          auth: "close"
        },
      ],
    };
  },
  methods: {

    setTransferStatus (status,row) {
      let copyRow = deepCopy(row);
      copyRow.status = status;
      for (let key in copyRow) {
        if (/_relation/g.test(key)) {
          delete copyRow[key]
        }
      }
      console.log(copyRow)
      save({
        table_name: 'transfers',
        ...copyRow
      }).then(_ => this.$refs['xyTable'].getTableData())
    },

    index,
    destroy,
    download,
    reset() {
      this.select.filter.splice(1);
      this.select.filter[0] = {
        key: "",
        op: "",
        value: "",
      };
    },

    async exportExcel(sheetName) {
      const res = await index(
        Object.assign(this.select, { page: 1, page_size: 9999 })
      );
      if (res.data) {
        let headers = this.form.map((i) => {
          return {
            key: i.field,
            title: i.name,
          };
        });
        const data = res.data.map((row) =>
          headers.map((header) => row[header.key])
        );
        data.unshift(headers.map((header) => header.title));
        const wb = XLSX.utils.book_new();
        const ws = XLSX.utils.aoa_to_sheet(data);
        XLSX.utils.book_append_sheet(wb, ws, sheetName);
        const wbout = XLSX.write(wb, {
          bookType: "xlsx",
          bookSST: true,
          type: "array",
        });
        saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          `${sheetName}.xlsx`
        );
      }
    },

    //target要为内存地址引用类型
    inputStartHandler(e, target) {
      let temp = target?.value.split(",")[1];
      target.value = `${e},${temp ? temp : ""}`;
    },
    inputEndHandler(e, target) {
      let temp = target?.value.split(",")[0];
      target.value = `${temp ? temp : ""},${e}`;
    },

    async getFormDetail() {
      if (this.$route.meta.params?.custom_form) {
        let decode = decodeURIComponent(this.$route.meta.params?.custom_form);
        try {
          let custom_form = JSON.parse(decode);
          this.customForm.customFormId = custom_form.custom_form_id;
          this.customForm.tableName = custom_form.table_name;
          this.select.table_name = custom_form.table_name;
        } catch (err) {
          console.warn(err);
        }
      }
      if (this.$route.meta.params?.select) {
        try {
          this.selectQuery = JSON.parse(
            decodeURIComponent(this.$route.meta.params?.select)
          );
        } catch (err) {
          console.warn(err);
        }
      }

      const res = await show({ id: this.customForm.customFormId }, false);

      //字段处理
      //初始表白名单
      let baseTable = new Map([
        [
          "departments",
          async () => {
            const res = await listdept();
            return res;
          },
        ],
        ["admins", []],
      ]);
      let { fields, relation } = res;
      let fieldRes = fields.sort((a, b) => a.sort - b.sort);
      if (
        !fields ||
        !relation ||
        !fields instanceof Array ||
        !relation instanceof Array
      ) {
        throw new Error("fields或relation格式错误");
      }
      fieldRes?.forEach((i, index) => {
        i._relations = relation.find((j) => j.custom_form_field === i.field);
        if (i.select_item && typeof i.select_item === "object") {
          let keys = Object.keys(i.select_item);
          if (keys.length > 0) {
            i._params = keys.map((key) => {
              return {
                key,
                value: /^\d*$/.test(i.select_item[key])
                  ? Number(i.select_item[key])
                  : i.select_item[key],
              };
            });
          }
        }
        if (i.edit_input === "file" || i.edit_input === "files") {
          return;
        }
        if (i._relations) {
          if (baseTable.get(i._relations.link_table_name)) {
            baseTable
              .get(i._relations.link_table_name)()
              .then((res) => (i._params = res));
          } else {
            i._params = i._relations.parameter_id
              ? getparameter({ id: i._relations.parameter_id }, false).then(
                (res) => {
                  i._params = res.detail;
                }
              )
              : this.index({
                table_name: i._relations.link_table_name,
                page: 1,
                page_size: 9999,
              }).then((res) => {
                i._params = res.data;
              });
          }
        }
      });
      this.form = fields;
    },

    adjustAlignment () {
      if (this.firstAdjustTable) {
        const data = this.$refs['xyTable'].getListData();
        if (data.length === 0) return;
        this.form.filter(i => i.list_show).forEach((i) => {
          let lengthTemp;
          let temp = 0;
          try {
            while (!lengthTemp || temp < data.length) {
              lengthTemp = data[temp][i.field]?.length??0;
              temp++;
            }
            for (let j = 0;j < data.length;j++) {
              if (/^-?\d+\.\d+/.test(data[j][i.field])) {
                this.table.find(a => a.prop === i.field).align = 'right';
                return
              }
              if (Math.abs(lengthTemp - (data[j][i.field]?.length)??0) > 4) {
                this.table.find(a => a.prop === i.field).align = 'left';
                return
              }
            }
          } catch (err) {
          }
        })
        this.$nextTick(() => {
          this.$refs['xyTable'].doLayout();
          this.firstAdjustTable = false;
        })
      }
    },

    async getAbility() {
      const obj = (await formFieldShow({ id: 31 }, false))?.select_item;
      if (obj && typeof obj === "object") {
        let keys = Object.keys(obj);
        if (keys.length > 0) {
          this.abilities = keys.map((key) => {
            return {
              key,
              value: /^\d*$/.test(obj[key]) ? Number(obj[key]) : obj[key],
            };
          });
        }
      }
    },
    async getEquipments () {
      const res = (await index({
        table_name: 'equipments',
        page: 1,
        page_size: 9999
      },false))?.data || []
      this.equipments = this.areas.map(i => ({
        id: `area_${i.value}`,
        name: i.key,
        children: res.filter(j => j.area === i.value)
      }))

      // this.$nextTick(() => {
      //   this.areas.forEach(i => {
      //     this.$refs['elTree'].setChecked(`area_${i.value}`, true, true)
      //   })
      // })
    },

    async getArea() {
      const obj = (await formFieldShow({ id: 4 }, false))?.select_item;
      if (obj && typeof obj === "object") {
        let keys = Object.keys(obj);
        if (keys.length > 0) {
          this.areas = keys.map((key) => {
            return {
              key,
              value: /^\d*$/.test(obj[key]) ? Number(obj[key]) : obj[key],
            };
          });
        }
      }
      await this.getEquipments()
    },

    async getDiaolingleixing() {
      const obj = {
        "逻辑调令": "4",
        "防汛调令": "2",
        "水环境调令": "1",
        "船只过闸调令": "3"
      };
      if (obj && typeof obj === "object") {
        let keys = Object.keys(obj);
        if (keys.length > 0) {
          this.diaolingleixing = keys.map((key) => {
            return {
              key,
              value: /^\d*$/.test(obj[key]) ? Number(obj[key]) : obj[key],
            };
          });
        }
      }
      this.$bus.$emit("diaolingleixing", this.abilities);
    },

    handleCheckChange (data, checked, indeterminate) {
      console.log(data)
      this.select.filter[2].value = data.filter(i => i)
      // this.treeValue = this.$refs['elTree'].getCheckedNodes(true)?.filter(i => !i.children)?.map(i => i.name).toString()
      // this.select.filter[2].value = this.$refs['elTree'].getCheckedNodes(true)?.filter(i => !i.children)?.map(i => i.id)
      //
      // this.$refs['xyTable'].getTableData(true)
    },
  },

  computed: {
    stepFormat () {
      return function (statue,s) {
        const doneStatus = Array.from({ length: statue },((_,i) => (i + 1)))
        if (statue === s) {
          return "doing"
        }
        if (doneStatus.find(i => i === s)) {
          return "done"
        }
        return false
      }
    },

    progressStatus () {
      return function (item) {
        if (item.tiaozhengleixing === 0) {
          return [
            {
              value: 2,
              label: "接收",
              auth: "receive"
            },
            {
              value: 3,
              label: "确认关闭通知",
              auth: "noticeClose"
            },
            {
              value: 4,
              label: "确认关闭",
              auth: "close"
            },
          ];
        } else if (item.tiaozhengleixing === 1) {
          if (item.equipment_id_equipments_id_relation?.type === 1) {
            return [
              {
                value: 2,
                label: "接收",
                auth: "receive"
              },
              {
                value: 3,
                label: "通知增开",
                auth: "noticeOpen"
              },
              {
                value: 4,
                label: "开启",
                auth: "open"
              },
            ]
          } else {
            return [
              {
                value: 2,
                label: "接收",
                auth: "receive"
              },
              {
                value: 3,
                label: "通知调整开度",
                auth: "noticeOpen"
              },
              {
                value: 4,
                label: "调整开度",
                auth: "open"
              },
            ]
          }
        } else {
          return this.status;
        }
      }
    },
    operateTitle () {
      return function (item, s) {
        switch (s.auth) {
          case 'receive':
            return item.receive_time
          case 'noticeOpen':
            return item.notice_open_time
          case 'open':
            return item.open_time
          case 'noticeClose':
            return item.notice_close_time
          case 'close':
            return item.close_time
          default:
            return ''
        }
      }
    },

    treeHeight () {
      return (this.$refs['xyTable']?.tableHeight + 36 || 630) + 'px'
    },

    columnArrTest() {
      return function (field) {
        return this.form.find((i) => i.field === field)
          ? this.form.find((i) => i.field === field).search_input ===
          "checkbox" ||
          this.form.find((i) => i.field === field).search_input === "radio"
          : false;
      };
    },
    getColumnField() {
      return function (field) {
        return this.form.find((i) => i.field === field)
          ? this.form.find((i) => i.field === field)
          : {};
      };
    },
    getColumnParams() {
      return function (field) {
        return this.form.find((i) => i.field === field)
          ? this.form.find((i) => i.field === field)._params
          : [];
      };
    },

    tableSelect() {
      let filter = [...this.select.filter, ...this.selectQuery];
      return {
        ...this.select,
        filter,
      };
    },
  },
  created() {
    this.getFormDetail();
    this.getAbility();
    this.getArea();
    this.getDiaolingleixing();
  },
};
</script>

<style scoped lang="scss">
.select {
  &__item {
    & > p {
      display: inline-block;
      width: 80px;
      text-align: center;
    }

    & + div {
      margin-top: 6px;
    }
  }
}
.add-btn {
  display: flex;
  justify-content: center;
  align-items: center;

  margin-top: 10px;
  & > span {
    padding: 0 10px;
  }
}

a {
  color: red;
  text-decoration: none;
  transition: all 0.2s;
}

a:hover {
  color: red;
  text-decoration: underline;
}

.list-item__operate {
  height: 4.8em;
  font-size: 11px;
  flex-basis: 22%;
  display: flex;
  align-items: center;
  justify-content: center;

  .step {
    width: 6.6em;

    &-icon {
      display: flex;
      align-items: center;
      justify-content: center;

      position: relative;

      $done-color: #ec6a5e;
      $doing-color: #7ccac8;
      &__cir {
        width: 2.2em;
        height: 2.2em;
        background: #dcdcdc;
        border-radius: 100%;

        z-index: 2;
        position: relative;
        &-doing {
          cursor: pointer;
          transform: scale(.9, .9);
          background: $doing-color;

          position: relative;

          &::before {
            content: "";
            width: 132%;
            height: 132%;
            border-radius: 100%;
            opacity: 0.4;
            background: $doing-color;
            transform: translate(-50%,-50%);
            animation: scale infinite ease-out 4s;

            position: absolute;
            left: 50%;
            top: 50%;
          }
          @keyframes scale {
            0%,100% {
              transform: translate(-50%,-50%);
            }
            50% {
              transform: translate(-50%,-50%) scale(1.1,1.1);
            }
          }
        }
        &-done {
          background: $done-color;
        }
      }
      &__line {
        width: 100%;
        height: 2px;
        background: #dcdcdc;

        position: absolute;
        left: 50%;

        &-done {
          background: $done-color;
        }
      }

    }
    &-label {
      text-align: center;
      font-size: 1.05em;
      line-height: 1.5;

      margin-top: 4px;
    }
  }
}
</style>
