<template>
  <div style="height:100%;width:100%;">
    <a-layout style="height:100%;width:100%;">
      <a-layout-sider
        :width="leftWidth"
        style="border-right:2px solid #d5d5ff;float:left"
        :style="{ 'max-height': testHeight + 'px', 'height': testHeight + 'px' }">
        <div class="tree" style="width: 100%; height: 100%; overflow: auto; display: inline-flex;">
          <a-tree
            :tree-data="treeData"
            @select="treeNodeClickHandler"
            :fieldNames="{ children: 'children', title: 'pnm', key: 'id' }"
            :autoExpandParent="false"
            ref="jigou_tree"
            style="height:100%;">
            <template #custom="item">
              <span style="float:left;">{{ 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"
              class="demo-form-inline"
              style="padding-left: 10px;">
              <a-form-item label="督查状态" style="min-width: 200px;">
                <a-select 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%;">
                                    <addvSearch
                                      v-model="adName"
                                      :maxHeight="300"
                                      :maxWidth="250"
                                      :rootAddCode="curAdcode_long"
                                      :level="&quot;3&quot;"
                                      :nameOrCode="'name'"></addvSearch>
                                  </a-form-item> -->
              <a-form-item label="对象名称" style="min-width: 23%;">
                <a-input v-model:value="name" placeholder="对象名称" />
              </a-form-item>
              <!-- <a-form-item label="工程规模" style="min-width: 23%;">
                      <a-select v-model:value="engScale" placeholder="工程规模" allow-clear>
                        <a-select-option v-for="item in engScales" :key="item.id">{{ item.name }}</a-select-option>
                      </a-select>
                    </a-form-item> -->
              <!-- <a-form-item label="所在组" style="min-width: 23%;">
                      <a-auto-complete
                        v-model="groupName"
                        allow-clear
                        placeholder="请输入内容"
                        :filter-option="querySearchAsync"
                        @select="handleSelect"/>
              </a-form-item> -->
              <a-form-item label="督查时间" style="min-width: 23%;">
                <div style="display: flex;">
                  <a-range-picker v-model:value="dateRange" format="YYYY-MM-DD" separator="至" allow-clear />
                </div>
              </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 === 'nm'">
              <a-tooltip placement="top">
                <template #title>
                  <span>{{ record.nm }}</span>
                </template>
                <span class="ellipsis150">{{ record.nm }}</span>
              </a-tooltip>
            </template>
            <template v-else-if="column.dataIndex === 'groupName'">
              <a-tooltip placement="top">
                <template #title>
                  <span>{{ record.groupName }}</span>
                </template>
                <span class="ellipsis150">{{ 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 === 'location'">
              <a-tooltip placement="top">
                <template #title>
                  <span>{{ record.location }}</span>
                </template>
                <span class="ellipsis200">{{ record.location }}</span>
              </a-tooltip>
            </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>
      <heHuWeiShiTianbao
        v-if="showShuiKuTianBao"
        :rowData="rowData"
        :currentObjectRgstrId="currentObjectRgstrId"
        :currentResCode="currentResCode"
        :currentObjectId="currentObjectId"
        :openType="openType"
        :currentObjectName="currentResName"
        :pType="pType"
        :inspType="inspType"
        @cancelHandler="cancelHandler"
        @addShuiKuSuccess="addShuiKuSuccess"> </heHuWeiShiTianbao>
    </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_hhws,
  getrgstrIdObjectById_hhws,
  getSKList_xsk,
} from '../../api/duChaTianBao.js';
import { curAdcode_long, curAdcode_short } from '../../utils/global_variable';
import request from '../../utils/gw_ajax_request.js';
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 heHuWeiShiTianbao from '../duChaTianBao/heHuWeiShiTianbao.vue';
import shuikuTianBaoPl from '../duChaTianBao/shuiKuTianbao_piliang.vue';
import { fillColumnForJiangxiHeHuWeiShi } from './hehuweishi/forDifferentProvince.js';
import rsvrInfo from './shuiku/skInfo/main.vue';

export default {
  components: {
    provTreeList: provTreeList,
    heHuWeiShiTianbao: heHuWeiShiTianbao,
    shuikuTianBaoPl: shuikuTianBaoPl,
    rsvrInfo: rsvrInfo,
    addvSearch,
  },
  data() {
    return {
      openType: '',
      name: '',
      isOpen: true,
      leftWidth: '320px',
      dateRange: [],
      lyjg: [],
      engScales: [
        { id: '4', name: '小（1）型' },
        { id: '5', name: '小（2）型' },
      ],
      engScale: '',
      orgName: '',
      groupName: '',
      groupId: '',
      groups: [],
      // sttm:'',
      // ettm:'',
      adName: '',
      treeData: [],
      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,
      zerenrenLabel: '"三个责任人"落实情况',
      pType: 50,
      fillTableData: [], // 根据不同省份赋值
      inspType: '',
      columns: [
        {
          title: '对象名称',
          dataIndex: 'nm',
          width: 150,
          fixed: 'left',
          align: 'center',
        },
        {
          title: '所在组',
          dataIndex: 'groupName',
          width: 150,
          align: 'center',
        },
        {
          title: '督查时间',
          dataIndex: 'intm',
          width: 120,
          align: 'center',
        },
        {
          title: '所在位置',
          dataIndex: 'location',
          width: 200,
          align: 'center',
        },
        {
          title: '督查状态',
          dataIndex: 'state',
          width: 200,
          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() {
    if (hasPriv('manage')) {
      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();

    if (this.currentRlcode.indexOf('36') == '0') {
      this.fillTableData = fillColumnForJiangxiHeHuWeiShi;
    } else if (this.currentRlcode.indexOf('35') == '0') {
      this.fillTableData = fillColumnForJiangxi;
    } else {
      this.fillTableData = fillColumnNation;
    }
  },
  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: '50' },
        })
        .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 = [];
      request
        .get('/dc/organization/base/getAllNode', {
          params: { userId: this.persId, orgType: '050' },
        })
        .then((res) => {
          let data = res.data;
          data.forEach((ele) => {
            if (ele.pid == null || ele.pid == '') {
              ele.pid = '050';
            }
            if (ele.id.length == 6) {
              this.lyjg.push(ele);
            }
          });
          data = this.getTrees(data);
          this.treeData = data;
          console.log(data);

          // _self.duChaType = _self.treeData[0].id.substring(2,3);
        });
    },
    // 格式化树形数据
    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');
      }
    },
    formatEngScal(row, column) {
      const engScal = row.engScal;
      let _engScal = '其他';
      switch (engScal) {
        case '1':
          _engScal = '大（1）型';
          break;
        case '2':
          _engScal = '大（2）型';
          break;
        case '3':
          _engScal = '中型';
          break;
        case '4':
          _engScal = '小（1）型';
          break;
        case '5':
          _engScal = '小（2）型';
          break;
        case '9':
          _engScal = '其他';
          break;
      }
      return _engScal;
    },
    getSkDataList: function () {
      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: 'rvlksf',
        presId: this.persId,
        pType: '50',
        pageSize: this.pageSize,
        pageNum: this.pageIndex,
        id: this.currentNodeId,
        name: this.name,
        state: this.dcType,
        adName: this.adName,
        sttm: paramStartDate,
        entm: paramEndDate,
        riverId: this.orgName,
        groupId: this.groupId,
      };
      getList_hhws(paramsData).then((res) => {
        console.log(res);
        res.data.list.forEach((item) => {
          if (item.intm) {
            item.intm = item.intm.substring(0, 10);
          }
        });
        this.skDataList = res.data.list;
        this.total = res.data.total;
      });
    },
    onSubmit() {
      this.getSkDataList();
    },
    toAddMember(type, rowData) {
      this.rowData = rowData;
      this.inspType = rowData.inspType;
      // ;
      console.log(rowData);
      // getrgstrIdObject(rowData.code,rowData.objId,_self.pageIndex).then(
      //   (res) =>{
      //     console.log(res);
      this.currentResCode = this.rowData.code;
      this.currentObjectId = this.rowData.objId;
      this.currentObjectRgstrId = this.rowData.rgstrId;
      this.currentResName = this.rowData.nm;
      this.showShuiKuTianBao = true;
      this.openType = true;
      // 获取完成
      //   },
      //   (err) =>{

      //   }
      // );
    },
    toCheck(rowData) {
      this.rowData = rowData;
      this.inspType = rowData.inspType;
      this.currentResCode = this.rowData.code;
      this.currentObjectId = this.rowData.objId;
      this.currentObjectRgstrId = this.rowData.rgstrId;
      this.currentResName = this.rowData.nm;
      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=50&objId=${obj.objId}`,
            )
            .then((res) => {
              if (res.success) {
                this.pageIndexChange();
                this.$message.success('删除成功');
              } else {
                this.$message.error(res.message);
              }
            });
        },
      });
    },
    submitHandler(rowData) {
      console.log(rowData);
      // optionsForJiangxi
      // 都要督查的数据的类别(运行管理、设备设施...)
      const duChaCategorys = this.fillTableData;
      getrgstrIdObjectById_hhws(rowData.rgstrId).then((res) => {
        if (res.data.state != '1') {
          this.$message({
            message: '河湖卫士填报未完成！',
            type: 'warning',
          });
          return;
        }
        this.$confirm({
          title: '提示',
          content: '确认退出吗？',
          okType: 'warning',
          onOk: () => {
            const formObj = {
              id: rowData.rgstrId,
              state: '2',
              objId: rowData.objId,
            };
            request.post('bis/insp/rvlksf/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) {
      console.log(val);
      this.pageIndex = val;
      this.getSkDataList();
    },
    handleSizeChange(size, val) {
      this.pageSize = val;
      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;
    },
    // 新需求  点击复查显示以前的督查信息
    toShowDuchaDetail(row) {
      this.currentResCode = row.code;
      this.currentObjectId = row.objId;
      this.currentObjectRgstrId = row.rgstrId;
      this.currentResName = row.nm;
      this.showDuchaDetails = true;
    },
    closeInfoDialog() {
      this.showDuchaDetails = false;
    },
    // 加入复查
    joinRecheck(row) {
      const data = {
        regerId: row.rgstrId,
        type: '1',
      };
      this.$confirm({
        title: '提示',
        content: '确定加入复查吗？',
        okType: 'warning',
        onOk: () => {
          request
            .post(`/bis/insp/repeat/check/log`, data)
            .then((res) => {
              if (res.success) {
                this.$message.success('已加入复查');
                this.getSkDataList();
              } else {
                this.$message.error(res.message);
              }
            })
            .catch((err) => {
              this.$message.error(err.message);
            });
        },
      });
    },
  },
};
</script>

<style lang='less' scoped>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

#dxdcListMainsk {
  overflow-y: hidden;
}

:deep(.ant-table-pagination) {
  float: left;
}

: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;
}

.ellipsis200 {
  display: block;
  width: 198px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

.ellipsis120 {
  display: block;
  width: 118px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

.ellipsis150 {
  display: block;
  width: 148px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

: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>
