<template>
  <div style="height: 100%; width: 100%;">
    <a-layout style="height:100%;width:100%;">
      <a-layout-sider theme="light" :width="leftWidth" style="border-right:2px solid #d5d5ff;float:left" :style="{'max-height':testHeight+'px','height':testHeight+'px'}">
        <div class="tree" style="height: 100%; width: 100%; overflow: auto; display: inline-flex;">
          <a-tree
            :tree-data="treeData"
            @select="treeNodeClickHandler"
            :fieldNames="{children: 'children', title: 'pnm', key: 'id'}"
            :auto-expand-parent="true"
            :expandedKeys.sync="expandedKeys"
            ref="jigou_tree"
            style="height:100%;">
            <template #custom="item">
              <span style="float:left;" :title="item.pnm"><span v-if="item.id && item.id.length >=12">
                <img src="../../assets/images/choucha.png" v-if="item.chkType=='0'" style="width: 25px;height:20px;float: left;" />
                <img src="../../assets/images/zicha.png" v-if="item.chkType=='1'" style="width: 25px;height:20px;float: left;" />&nbsp;
              </span>{{ item.pnm?(item.pnm.length>12?(item.pnm.substring(0,10))+"...":item.pnm):"" }}</span>
            </template>
          </a-tree>
        </div>
      </a-layout-sider>
      <a-layout-content id="dxdcListMainsk" style="padding:5px 20px;position:relative;">
        <a-row>
          <a-col :span="24">
            <a-form layout="inline">
              <a-form-item label="督查状态" style="min-width: 23%;">
                <a-select style="min-width: 120px;" v-model:value="dcType" placeholder="督查状态" allow-clear>
                  <a-select-option value="0">未督查</a-select-option>
                  <a-select-option value="1">督查中</a-select-option>
                  <a-select-option value="2">已督查</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="对象名称" style="min-width: 23%;">
                <a-input v-model:value="nm" placeholder="对象名称" />
              </a-form-item>
              <a-form-item label="督查时间" style="min-width: 23%;">
                <a-range-picker v-model:value="dateRange" format="YYYY-MM-DD" separator="至" allow-clear />
              </a-form-item>
              <a-form-item>
                <a-button type="primary" @click="onSubmit" size="small" >查询</a-button>
              </a-form-item>
            </a-form>
          </a-col>
        </a-row>
        <a-table
          ref="table"
          :columns="columns"
          :data-source="skDataList"
          :loading="expLoading"
          :pagination="false"
          row-key="rgstrId"
          style="width: 100%;"
          :style="{height: tableHeight + 'px'}"
          :scroll="{x: 'max-content', y: tableHeight - 60}"
          bordered>
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'name'">
              <a-tooltip placement="top">
                <template #title>
                  <span>{{ record.name }}</span>
                </template>
                <span class="ellipsis150">{{ record.name }}</span>
              </a-tooltip>
            </template>
            <template v-else-if="column.dataIndex === 'province'">
              <a-tooltip placement="top">
                <template #title>
                  <span>{{ record.province }}</span>
                </template>
                <span class="ellipsis100">{{ record.province }}</span>
              </a-tooltip>
            </template>
            <template v-else-if="column.dataIndex === 'city'">
              <a-tooltip placement="top">
                <template #title>
                  <span>{{ record.city }}</span>
                </template>
                <span class="ellipsis100">{{ record.city }}</span>
              </a-tooltip>
            </template>
            <template v-else-if="column.dataIndex === 'country'">
              <a-tooltip placement="top">
                <template #title>
                  <span>{{ record.country }}</span>
                </template>
                <span class="ellipsis100">{{ record.country }}</span>
              </a-tooltip>
            </template>
            <template v-else-if="column.dataIndex === 'hystType'">
              <a-tooltip placement="top">
                <template #title>
                  <span>{{ record.hystType }}</span>
                </template>
                <span class="ellipsis100">{{ record.hystType }}</span>
              </a-tooltip>
            </template>
            <template v-else-if="column.dataIndex === 'damTypeMat'">
              <a-tooltip placement="top">
                <template #title>
                  <span>{{ record.damTypeMat }}</span>
                </template>
                <span class="ellipsis120">{{ record.damTypeMat }}</span>
              </a-tooltip>
            </template>
            <template v-else-if="column.dataIndex === 'insCap'">
              <a-tooltip placement="top">
                <template #title>
                  <span>{{ record.insCap }}</span>
                </template>
                <span class="ellipsis130">{{ record.insCap }}</span>
              </a-tooltip>
            </template>
            <template v-else-if="column.dataIndex === 'totCap'">
              <a-tooltip placement="top">
                <template #title>
                  <span>{{ record.totCap }}</span>
                </template>
                <span class="ellipsis130">{{ record.totCap }}</span>
              </a-tooltip>
            </template>
            <template v-else-if="column.dataIndex === 'groupName'">
              <a-tooltip placement="top">
                <template #title>
                  <span>{{ record.groupName }}</span>
                </template>
                <span class="ellipsis120">{{ record.groupName }}</span>
              </a-tooltip>
            </template>
            <template v-else-if="column.dataIndex === 'intm'">
              <a-tooltip placement="top">
                <template #title>
                  <span>{{ record.intm }}</span>
                </template>
                <span class="ellipsis120">{{ record.intm }}</span>
              </a-tooltip>
            </template>
            <template v-else-if="column.dataIndex === 'loc'">
              <a-tooltip placement="top">
                <template #title>
                  <span>{{ record.loc }}</span>
                </template>
                <span class="ellipsis150">{{ record.loc }}</span>
              </a-tooltip>
            </template>
            <template v-else-if="column.dataIndex === 'jxqState' || column.dataIndex === 'jxmonState' || column.dataIndex === 'safState'">
              <p style="cursor:pointer;color:#F56C6C;" v-if="record[column.dataIndex] == '0' || !record[column.dataIndex]">待填报</p>
              <p style="cursor:pointer;color:#fbb56d" v-else-if="record[column.dataIndex] == '1'">未完成</p>
              <p style="cursor:pointer;color:#67C23A" v-else-if="record[column.dataIndex] == '2'">已完成</p>
            </template>
            <template v-else-if="column.dataIndex === 'state'">
              <span
                style="padding: 3px 10px;background:#F56C6C;border-radius:15px;color:rgba(255,255,255,1)"
                v-if="record.state == 0">未督查</span>
              <span
                style="padding: 3px 10px;background:#FBB56D;border-radius:15px;color:rgba(255,255,255,1)"
                v-else-if="record.state == 1">督查中</span>
              <span
                style="padding: 3px 10px;background:#63C25E;border-radius:15px;color:rgba(255,255,255,1)"
                v-else-if="record.state == 2">已督查</span>
            </template>
            <template v-else-if="column.dataIndex === 'action'">
              <a-button
                size="small"
                v-if="!record.rgstrId"
                ghost
                @click="toAddMember('填报',record)"
                type="primary">填报
              </a-button>
              <a-button
                size="small"
                v-if="record.rgstrId"
                ghost
                @click="toAddMember('编辑',record)"
                :disabled="record.state == '2'"
                type="primary">督查</a-button>
              <a-button
                size="small"
                type="danger"
                v-if="record.rgstrId"
                ghost
                @click="deleteMember(record)"
                :disabled="record.state == '2'">删除</a-button>
              <a-button
                size="small"
                type="danger"
                v-if="record.rgstrId"
                ghost
                @click="submitHandler(record)"
                :disabled="record.state == '2'">提交</a-button>
              <a-button
                size="small"
                v-if="record.rgstrId && record.state == '2'"
                ghost
                @click="toCheck(record)"
                type="primary">查看</a-button>
            </template>
          </template>
        </a-table>
        <a-pagination
          show-size-changer
          v-model:pageSize="pageSize"
          :total="total"
          :page-size-options="['10','20', '30', '40', '50','100']"
          :show-total="total => `共${total}条`"
          @showSizeChange="handleSizeChange"
          @change="pageIndexChange"
          style="margin-top: 10px;" />
        <div class="open_board">
          <a-icon type="left" v-if="isOpen" @click="closeLeft" />
          <a-icon type="right" v-else @click="openLeft" />
        </div>
      </a-layout-content>
      <xiaoShuiDianTianBao
        v-if="showShuiKuTianBao"
        :rowData="rowData"
        :currentObjectRgstrId="currentObjectRgstrId"
        :currentResCode="currentResCode"
        :currentObjectId="currentObjectId"
        :id="id"
        :openType="openType"
        :currentObjectName="currentResName"
        :pType="pType"
        @cancelHandler="cancelHandler"
        @addShuiKuSuccess="addShuiKuSuccess"> </xiaoShuiDianTianBao>
    </a-layout>
    <!-- 上传模板弹窗 -->
    <shuiku-tian-bao-pl
      v-if="showShuiKuTianBaoPl"
      :showShuiKuTianBaoPl="showShuiKuTianBaoPl"
      :id="currentNodeId"
      @closePlDialog="closePlDialog"></shuiku-tian-bao-pl>
    <!-- 水库信息查看 -->
    <rsvr-info
      :currentObjectRgstrId="currentObjectRgstrId"
      :currentResCode="currentResCode"
      :currentObjectId="currentObjectId"
      :currentObjectName="currentResName"
      :isJiangXi="isJiangXi"
      v-if="showDuchaDetails"
      @cancelHandler="closeInfoDialog"></rsvr-info>
  </div>
</template>

<script>
import {
  getList_xshd,
  getrgstrIdObjectById_hystjx,
  getSKList_xsk,
} from '../../api/duChaTianBao.js';
import {
  curAdcode_long,
  curAdcode_short,
} from '../../utils/global_variable.js';
import request from '../../utils/gw_ajax_request';
import { dateFormat } from '../../utils/gw_date.js';
import { exportModel } from '../../utils/gw_exportModel';
import addvSearch from '../../widgets/addvSearch.vue';
import provTreeList from '../../widgets/provTreeList.vue';
import shuikuTianBaoPl from '../duChaTianBao/shuiKuTianbao_piliang.vue';
import xiaoShuiDianTianBao from '../duChaTianBao/xiaoShuiDianTianBao.vue';
import rsvrInfo from './shuiku/skInfo/main.vue';
import { fillColumnForJiangxiShuJun } from './shujunshashi/forDifferentProvince.js';
export default {
  components: {
    provTreeList: provTreeList,
    xiaoShuiDianTianBao: xiaoShuiDianTianBao,
    shuikuTianBaoPl: shuikuTianBaoPl,
    rsvrInfo: rsvrInfo,
    addvSearch,
  },
  data() {
    return {
      openType: '',
      isOpen: true,
      leftWidth: '320px',
      dateRange: [],
      lyjg: [],
      id: '',
      nm: '',
      engScale: '',
      orgName: '',
      groupName: '',
      groupId: '',
      groups: [],
      adName: '',
      treeData: [],
      expandedKeys: [],
      dxdcMainHeight: window.innerHeight - 304,
      testHeight: window.innerHeight - 111,
      skDataList: [],
      pageIndex: 1,
      pageSize: 20,
      total: 0,
      tableHeight: 0,
      currentResCode: '',
      currentResName: '',
      currentObjectId: '',
      currentObjectRgstrId: '',
      currentObjectInfoObject: null,
      showShuiKuTianBao: false,
      currentAdCode: '',
      currentNodeId: '',
      rsvrName: '',
      dcType: '',
      rowData: '',
      disabled: true,
      showShuiKuTianBaoPl: false,
      downIcon: 'el-icon-download',
      expLoading: false,
      //
      repeatId: '',
      showDuchaDetails: false,
      pType: 59,
      fillTableData: [
        {
          value: 'jxqState',
          label: '生态流量泄放情况',
        },
        {
          value: 'jxmonState',
          label: '生态流量监测情况',
        },
        {
          value: 'safState',
          label: '大坝安全情况',
        },
      ],
      columns: [
        {
          title: '对象名称',
          dataIndex: 'name',
          width: 150,
          fixed: 'left',
          align: 'center',
        },
        {
          title: '省',
          dataIndex: 'province',
          width: 100,
          align: 'center',
        },
        {
          title: '市',
          dataIndex: 'city',
          width: 100,
          align: 'center',
        },
        {
          title: '县',
          dataIndex: 'country',
          width: 100,
          align: 'center',
        },
        {
          title: '开发方式',
          dataIndex: 'hystType',
          width: 100,
          align: 'center',
        },
        {
          title: '大坝坝型',
          dataIndex: 'damTypeMat',
          width: 120,
          align: 'center',
        },
        {
          title: '电站规模（kw）',
          dataIndex: 'insCap',
          width: 130,
          align: 'center',
        },
        {
          title: '总库容（万m3）',
          dataIndex: 'totCap',
          width: 130,
          align: 'center',
        },
        {
          title: '所在组',
          dataIndex: 'groupName',
          width: 120,
          align: 'center',
        },
        {
          title: '督查时间',
          dataIndex: 'intm',
          width: 120,
          align: 'center',
        },
        {
          title: '所在位置',
          dataIndex: 'loc',
          width: 150,
          align: 'center',
        },
      ],
    };
  },
  computed: {
    persId() {
      return localStorage.getItem('persId')
        ? localStorage.getItem('persId')
        : '1098101939614724096';
    },
    isAdmin: () =>
      localStorage.getItem('isAdmin') ? localStorage.getItem('isAdmin') : '',
    currentRlcode() {
      return localStorage.getItem('currentRlcode')
        ? localStorage.getItem('currentRlcode')
        : '';
    },
    isJiangXi() {
      return this.currentRlcode.indexOf('36') == '0';
    },
    curAdcode_short() {
      return curAdcode_short;
    },
    curAdcode_long() {
      return curAdcode_long;
    },
  },
  created() {
    this.fillTableData.forEach((item) => {
      const obj = {
        title: item.label,
        dataIndex: item.value,
        width: 140,
        align: 'center',
      };
      this.columns.push(obj);
    });
    this.columns.push({
      title: '督查状态',
      dataIndex: 'state',
      width: 130,
      align: 'center',
    });
    this.columns.push({
      title: '操作',
      dataIndex: 'action',
      width: 330,
      align: 'center',
      fixed: 'right',
    });
  },
  mounted() {
    this.$nextTick(function () {
      this.tableHeight =
        window.innerHeight - this.$refs.table.$el.offsetTop - 200;
      window.onresize = () => {
        this.tableHeight =
          window.innerHeight - this.$refs.table.$el.offsetTop - 200;
      };
    });
    this.getLeftTreeData();
    this.currentNodeId = '';
    this.rsvrName = '';
    this.dcType = '';
    this.getSkDataList();
    this.getAllGroup();
  },
  watch: {
    currentNodeId(n, o) {
      this.getSkDataList();
    },
    groupName(n, o) {
      if (n == '') {
        this.groupId = '';
      }
    },
  },
  methods: {
    closeLeft() {
      this.isOpen = false;
      this.leftWidth = '0';
      // this.rightWidth = 24
    },
    openLeft() {
      this.isOpen = true;
      this.leftWidth = '320px';
      // this.rightWidth = 19
    },
    // 获取所有的组
    getAllGroup() {
      request
        .get('/dc/user/getGroupByPersid', {
          params: { persid: this.persId, ptype: '59' },
        })
        .then((res) => {
          if (res.success) {
            this.groups = res.data;
          }
        });
    },
    querySearchAsync(queryString, cb) {
      var restaurants = this.groups;
      var results = queryString
        ? restaurants.filter(this.createStateFilter(queryString))
        : restaurants;

      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 1500 * Math.random());
    },
    createStateFilter(queryString) {
      return (state) => {
        return state.nm.toLowerCase().indexOf(queryString.toLowerCase()) != -1;
      };
    },
    handleSelect(item) {
      console.log(item);
      this.groupId = item.id;
    },
    getLeftTreeData() {
      this.lyjg = [];
      this.expandedKeys = [];
      request
        .get('/dc/organization/base/getAllNode', {
          params: { userId: this.persId, orgType: '059' },
        })
        .then((res) => {
          let data = res.data;
          data.forEach((ele) => {
            if (ele.pid == null || ele.pid == '') {
              ele.pid = '059';
            }
            if (ele.id.length == 6) {
              this.lyjg.push(ele);
            }
          });
          data = this.getTrees(data);
          this.treeData = data;
          this.expandedKeys.push(data[0].id);
        });
    },
    // 格式化树形数据
    getTrees(list) {
      // @wxcwater重写方法 适应多个树
      let highLevelLength = 99; // 预设最大节点id长度，目前最大应该为12，所以设置为99保证正常
      list.forEach((item, index) => {
        item['pidLength'] = item.pid && item.pid != '' ? item.pid.length : 0;
        if (highLevelLength > item.pidLength) {
          highLevelLength = item.pidLength;
        }
      });
      console.log(highLevelLength);
      const heightLevelNode = [];
      list.forEach((item, index) => {
        if (highLevelLength >= item.pidLength) {
          heightLevelNode.push(item);
        }
      });

      list.forEach((item, index) => {
        heightLevelNode.forEach((pItem) => {
          this.addTreeNode(pItem, item);
        });
      });
      console.log(heightLevelNode);
      return heightLevelNode;
    },
    addTreeNode: function (treeNode, leafNode) {
      if (!Object.hasOwn(treeNode, 'children')) {
        treeNode['children'] = [];
      }
      if (leafNode.pid == treeNode.id) {
        treeNode.children.push(leafNode);
        return;
      }
      treeNode.children.forEach((item) => {
        this.addTreeNode(item, leafNode);
      });
    },
    treeNodeClickHandler: function (data, node, tree) {
      this.currentNodeId = data[0];
    },
    provTreeSelectChangeHandler: function (params) {
      this.currentAdCode = params.likeCode;
      this.getSkDataList();
    },
    formatDate(row, column) {
      if (row.uptm) {
        return dateFormat(row.uptm, 'yyyy-MM-dd');
      }
    },
    getSkDataList() {
      let paramStartDate = '';
      let paramEndDate = '';
      if (
        this.dateRange &&
        this.dateRange.length > 1 &&
        this.dateRange[0] != '' &&
        this.dateRange[1] != ''
      ) {
        paramStartDate = this.dateRange[0];
        paramEndDate = this.dateRange[1];
      }
      const paramsData = {
        type: 'hystjx',
        presId: this.persId,
        pType: '59',
        pageSize: this.pageSize,
        pageNum: this.pageIndex,
        id: this.currentNodeId,
        name: this.nm,
        state: this.dcType,
        adName: this.adName,
        sttm: paramStartDate,
        entm: paramEndDate,
        riverId: this.orgName,
        groupId: this.groupId,
      };
      getList_xshd(paramsData).then((res) => {
        console.log(res);
        res.data.list.forEach((item) => {
          if (item.intm && typeof item.intm === 'string') {
            item.intm = item.intm.substring(0, 10);
          } else {
            item.intm = dateFormat(item.intm, 'yyyy-MM-dd');
          }
        });
        this.skDataList = res.data.list;
        this.total = res.data.total;
      });
    },
    onSubmit() {
      this.getSkDataList();
    },
    toAddMember(type, rowData) {
      this.rowData = rowData;

      console.log(rowData);
      this.currentResCode = this.rowData.code;
      this.currentObjectId = this.rowData.objId;
      this.currentObjectRgstrId = this.rowData.rgstrId;
      this.currentResName = this.rowData.nm;
      this.id = this.rowData.id;
      this.showShuiKuTianBao = true;
      this.openType = true;
    },
    toCheck(rowData) {
      this.rowData = rowData;
      this.currentResCode = this.rowData.code;
      this.currentObjectId = this.rowData.objId;
      this.currentObjectRgstrId = this.rowData.rgstrId;
      this.currentResName = this.rowData.nm;
      this.id = this.rowData.id;
      this.showShuiKuTianBao = true;
      this.openType = false;
    },
    cancelHandler() {
      this.showShuiKuTianBao = false;
    },
    addShuiKuSuccess() {
      this.getSkDataList();
      this.showShuiKuTianBao = false;
    },
    deleteMember(obj) {
      console.log(obj);
      // /dc/insp/rsvrRgstr/delete/{id}
      this.$confirm({
        title: '提示',
        content: '此操作将督查对象从列表中删除，确认删除该对象吗？',
        okType: 'warning',
        onOk: () => {
          request
            .get(
              `/supervision/plan/cleanObjDataByObjId?objType=59&objId=${obj.objId}`,
            )
            .then((res) => {
              if (res.success) {
                this.pageIndexChange();
                this.$message.success('删除成功');
              } else {
                this.$message.error(res.message);
              }
            });
        },
      });
    },
    submitHandler(rowData) {
      getrgstrIdObjectById_hystjx(rowData.rgstrId).then((res) => {
        if (res.data.jxqState != '2') {
          this.$message.warning('生态流量泄放情况填报未完成');
          return;
        } else if (res.data.jxmonState != '2') {
          this.$message.warning('生态流量监测情况填报未完成');
          return;
        } else if (res.data.safState != '2') {
          this.$message.warning('大坝安全情况填报未完成');
          return;
        }
        this.$confirm({
          title: '提示',
          content: '请确认所有信息填报完毕？',
          okType: 'warning',
          onOk: () => {
            const formObj = {
              id: rowData.rgstrId,
              state: '2',
              objId: rowData.objId,
            };
            request.post('/bis/insp/hystjx/update', formObj).then((res) => {
              if (res.success) {
                request
                  .get('/dc/insp/pblm/submit/updateState/' + rowData.objId)
                  .then((res) => {
                    if (res.success) {
                      this.addShuiKuSuccess();
                      this.$message.success('提交成功');
                    } else {
                      this.cancelHandler();
                    }
                  });
              } else {
                this.cancelHandler();
              }
            });
          },
        });
      });
    },
    pageIndexChange(val) {
      this.pageIndex = val;
      this.getSkDataList();
    },
    handleSizeChange(val, size) {
      this.pageSize = size;
      this.getSkDataList();
    },
    // 下载填报模板
    async downloadTemplate() {
      const url =
        '/pdcApi/dc/impExcel/downloadTemplate/sk?userId=' +
        this.persId +
        '&id=' +
        this.currentNodeId;
      const downloadName = '小水库填报模板.xls';
      const type = 'get';
      await exportModel(type, url, downloadName);
      this.disabled = false;
    },
    showPlDialog() {
      this.showShuiKuTianBaoPl = true;
    },
    closePlDialog(val) {
      this.showShuiKuTianBaoPl = false;
    },
    closeInfoDialog() {
      this.showDuchaDetails = false;
    },
  },
};
</script>

<style lang='less' scoped>
/deep/ .ant-table-pagination {
  float: left;
}

/deep/ .warning-row {
  background: oldlace;
}

/deep/ .success-row {
  background: #f0f9eb;
}

#dxdcListMainsk {
  overflow-y: hidden;
}
/deep/ .ant-layout-sider,
/deep/ .ant-layout-content {
  background: #fff;
}

/deep/ .ant-table-thead>tr>th,
/deep/ .ant-table-tbody>tr>td {
  padding: 0;
  height: 60px;
}
.ellipsis100 {
  display: block;
  width: 98px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
.ellipsis120 {
  display: block;
  width: 118px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
.ellipsis130 {
  display: block;
  width: 128px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
.ellipsis150 {
  display: block;
  width: 148px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
.ant-table /deep/ td {
  white-space: nowrap;
}
/deep/ .ant-table-scroll {
  position: relative;
  z-index: 1;
}

/deep/.ant-table-fixed-left,
/deep/ .ant-table-fixed-right {
  z-index: 2;
}
.open_board {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 24px;
  height: 30px;
  line-height: 30px;
  border: solid 1px #ddd;
  border-top-right-radius: 5px;
  border-bottom-right-radius: 5px;
  text-align: center;
  background-color: #bbebff;
  cursor: pointer;
}
</style>
