<template>
  <div style="height:100%;width:100%;">
    <a-layout style="height:100%;width:100%;">
      <a-layout-sider width="320px" style="border-right:2px solid #d5d5ff;float:left" :style="{ 'max-height': testHeight + 'px', 'height': testHeight + 'px' }">
        <div class="tree" style="height: calc(100% - 50px); width: 100%; overflow: auto; display: inline-flex;">
          <a-tree
            :tree-data="treeData"
            @select="treeNodeClickHandler"
            :fieldNames="{ children: 'children', title: 'pnm', key: 'id' }"
            :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;">
        <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: 19%;">
                <a-select v-model:value="prjType" placeholder="督查事项" allow-clear>
                  <a-select-option v-for="item in prjTypeList" :key="item.dictTypeNum" :value="item.dictTypeNum">{{ item.nm }}</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="督查状态:" style="min-width: 19%;">
                <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: 19%;">
                <a-input v-model:value="depName" placeholder="对象名称" allow-clear />
              </a-form-item>
              <a-form-item label="是否申请信息调整:" style="min-width: 19%;">
                <a-select v-model:value="adjustState" placeholder="是否申请信息调整" allow-clear>
                  <a-select-option value="1">是</a-select-option>
                  <a-select-option value="2">否</a-select-option>
                </a-select>
              </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="tableData"
          :pagination="false"
          :loading="tableLoading"
          row-key="rgstrId"
          style="width: 100%; margin-top: 10px;"
          :style="{ height: tableHeight + 'px'}"
          :scroll="{ y: tableHeight - 60 }"
          bordered>
          <template slot="chkType" slot-scope="">
            <img src="../../assets/images/choucha.png" style="width: 25px;height:20px;" />
          </template>
          <template slot="state" slot-scope="text">
            <span v-if="text.state == 0" style="padding: 3px 10px;background:#F56C6C;border-radius:15px;color:rgba(255,255,255,1)">未督查</span>
            <span v-if="text.state == 1" style="padding: 3px 10px;background:#FBB56D;border-radius:15px;color:rgba(255,255,255,1)">督查中</span>
            <span v-if="text.state == 2" style="padding: 3px 10px;background:#63C25E;border-radius:15px;color:rgba(255,255,255,1)">已督查</span>
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'action'">
              <div style="display: flex; justify-content: center;">
                <a-button v-if="readOnlyRole == 'display'" @click="toAddMember(record)" :disabled="record.state == '2'" size="small" type="primary" ghost>督查</a-button>
                <a-button v-if="readOnlyRole == 'display'" @click="submitHandler(record)" :disabled="record.state == '2'" size="small" type="danger" ghost>提交</a-button>
                <a-button v-if="record.state == '2' && readOnlyRole == 'display'" @click="toCheck(record)" type="primary" size="small" ghost>查看</a-button>
                <a-button v-if="record.state == '2' && readOnlyRole == 'display'" @click="revoke(record)" type="danger" size="small" ghost>撤回</a-button>
              </div>
            </template>
          </template>
        </a-table>
        <a-pagination
          :current="pageIndex"
          show-size-changer
          :pageSize.sync="pageSize"
          :total="total"
          :page-size-options="['10', '20', '30', '40', '50', '100']"
          :show-total="total => `共${total}条`"
          @showSizeChange="handleSizeChange"
          @change="pageIndexChange"
          style="margin-top: 10px;" />
      </a-layout-content>

      <commonTab
        v-if="showShuiKuTianBao"
        :rowData="rowData"
        :currentObjectRgstrId="currentObjectRgstrId"
        :currentResCode="currentResCode"
        :currentObjectId="currentObjectId"
        :currentObjectName="currentResName"
        :pType="pType"
        :openType="openType"
        :chkType="chkType"
        @cancelHandler="cancelHandler"
        @addShuiKuSuccess="addShuiKuSuccess"
        :flag="0">
      </commonTab>

      <!-- 水库督查信息 -->
      <popupSk
        ref="xskTianBaoRef"
        v-if="xskInfoDialog"
        :currentDuchaTpe="currentDuchaTpe"
        :currentObjectRgstrId="xskRgstrId"
        :currentResCode="currentRsCode"
        :currentObjectId="currentObjId"
        :currentObjectName="currentRsName"
        @cancelHandler="skCancelHandler">
      </popupSk>
    </a-layout>
  </div>
</template>

<script>
import request from '@/utils/gw_ajax_request';
import { dateFormat } from '@/utils/gw_date';
import commonTab from './commonTabSxzhdctb.vue';
export default {
  data() {
    return {
      testHeight: 0,
      tableHeight: 0,
      treeData: [],
      treeList: [],
      currentNodeId: '',
      expandedKeys: [],
      prjType: undefined,
      prjTypeList: [],
      dcType: undefined,
      adjustState: undefined,
      depName: '',
      columns: [
        {
          title: '对象名称',
          dataIndex: 'nm',
          width: 150,
          align: 'center',
          ellipsis: true,
        },
        {
          title: '行政区划',
          dataIndex: 'adName',
          width: 150,
          align: 'center',
          ellipsis: true,
        },
        {
          title: '督查分类',
          dataIndex: 'chkType',
          width: 100,
          align: 'center',
        },
        {
          title: '督查事项',
          dataIndex: 'typeName',
          width: 150,
          align: 'center',
          ellipsis: true,
        },
        {
          title: '督查状态',
          dataIndex: 'state',
          width: 100,
          align: 'center',
        },
        {
          title: '上一次督查完成时间',
          dataIndex: 'intm1',
          width: 180,
          align: 'center',
          ellipsis: true,
        },
        {
          title: '经度',
          dataIndex: 'gdX',
          width: 100,
          align: 'center',
          ellipsis: true,
        },
        {
          title: '纬度',
          dataIndex: 'gdY',
          width: 100,
          align: 'center',
          ellipsis: true,
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
        },
      ],
      tableData: [],
      tableLoading: false,
      pageIndex: 1,
      pageSize: 20,
      total: 0,
      rowData: null,
      currentResCode: '',
      currentObjectId: '',
      currentObjectRgstrId: '',
      currentResName: '',
      showShuiKuTianBao: false,
      openType: false,
      chkType: '',
      pType: '111',
      xskInfoDialog: false,
      readOnlyRole: localStorage.getItem('readOnlyRole'),
    };
  },
  components: {
    commonTab,
  },
  computed: {
    persId() {
      return localStorage.getItem('persId')
        ? localStorage.getItem('persId')
        : '1098101939614724096';
    },
  },
  watch: {
    currentNodeId(n, o) {
      this.getTableList();
    },
  },
  created() {
    this.getLeftTreeData();
    this.getPrjType();
  },
  mounted() {
    // 浏览器自适应
    this.testHeight = window.innerHeight - 100;
    this.tableHeight = window.innerHeight - 240;
    window.addEventListener('resize', () => {
      return (() => {
        this.testHeight = window.innerHeight - 100;
        this.tableHeight = window.innerHeight - 240;
      })();
    });
  },
  methods: {
    // 获取左侧树数据
    getLeftTreeData() {
      this.expandedKeys = [];
      request
        .get('/dc/organization/base/getAllNode', {
          params: { userId: this.persId, orgType: '112', groupType: '1' },
        })
        .then((res) => {
          let data = res.data;
          this.treeList = res.data;
          data.forEach((ele) => {
            if (ele.pid == null || ele.pid == '') {
              ele.pid = '111';
            }
          });
          data = this.getTrees(data);
          this.treeData = data;
          this.treeData.forEach((item) => {
            if (item.children && item.children.length > 0) {
              item.children.forEach((item1) => {
                if (item1.children && item1.children.length > 0) {
                  item1.children.forEach((item2) => {
                    item2.scopedSlots = { title: 'custom' };
                  });
                }
              });
            }
          });
          if (data[0]) {
            this.currentNodeId = data[0].id;
            this.expandedKeys.push(data[0].id);
          } else {
            this.currentNodeId = '112';
          }
        });
    },
    // 格式化树形数据
    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;
        }
      });
      const heightLevelNode = [];
      list.forEach((item, index) => {
        if (highLevelLength >= item.pidLength) {
          heightLevelNode.push(item);
        }
      });

      list.forEach((item, index) => {
        heightLevelNode.forEach((pItem) => {
          this.addTreeNode(pItem, item);
        });
      });
      return heightLevelNode;
    },
    addTreeNode(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(data, node) {
      this.currentNodeId = data[0];
    },
    // 获取督查事项下拉框数据
    getPrjType() {
      const params = {
        type: 'province',
        displayStat: '0',
      };
      request
        .post('/bis/insp/BisInspProblemRelation/getCountyDcList', { params })
        .then((res) => {
          if (res.success) {
            this.prjTypeList = res.data;
          } else {
            this.$message.error(res.message);
          }
        })
        .catch(() => {
          this.$message.error('请求失败,请联系管理员!');
        });
    },
    onSubmit() {
      this.pageIndex = 1;
      this.getTableList();
    },
    // 获取表格数据
    getTableList() {
      this.tableLoading = true;
      const params = {
        prjType: this.prjType,
        presId: this.persId,
        pType: '111',
        pageSize: this.pageSize,
        pageNum: this.pageIndex,
        plnaId: this.currentNodeId || '112',
        state: this.dcType,
        nm: this.depName,
        adjustState: this.adjustState,
      };
      request.post(`/dc/insp/rsvrRgstr/list/type`, params).then((res) => {
        if (res.success) {
          res.data.list.forEach((item) => {
            if (item.intm) {
              item.intm1 = dateFormat(item.intm, 'yyyy-MM-dd');
            }
          });
          this.tableData = res.data.list;
          this.total = res.data.total;
          this.tableLoading = false;
        }
      });
    },
    handleSizeChange(size, val) {
      this.pageSize = val;
      this.getTableList();
    },
    pageIndexChange(val) {
      this.pageIndex = val;
      this.getTableList();
    },
    toAddMember(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.showShuiKuTianBao = true;
      this.openType = true;
      this.chkType = this.rowData.chkType;
    },
    cancelHandler() {
      this.showShuiKuTianBao = false;
      this.getTableList();
    },
    addShuiKuSuccess() {
      this.getTableList();
    },
    deleteMember(obj) {
      this.$confirm({
        title: '提示',
        content: '此操作将督查对象从列表中删除，确认删除该对象吗？',
        okType: 'warning',
        onOk: () => {
          request
            .get(
              `/supervision/plan/cleanObjDataByObjId?objType=111&objId=${obj.objId}&deleteMethod=1`,
            )
            .then((res) => {
              if (res.success) {
                this.pageIndexChange();
                this.$message.success('删除成功');
              } else {
                this.$message.error(res.message);
              }
            });
        },
      });
    },
    submitHandler(rowData) {
      this.$confirm({
        title: '提示',
        content: '请确认所有信息填报完毕？',
        okType: 'warning',
        onOk: () => {
          const formObj = {
            rgstrId: rowData.rgstrId,
            state: '2',
          };
          request.post('/bis/insp/gnrl', 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();
            }
          });
        },
      });
    },
    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.showShuiKuTianBao = true;
      this.openType = false;
      this.chkType = this.rowData.chkType;
      this.$nextTick(() => {
        if (this.$refs['xskTianBaoRef']) {
          this.$refs['xskTianBaoRef'].showDialog();
        }
      });
    },
    skCancelHandler() {
      this.xskInfoDialog = false;
    },
    revoke(rowData) {
      this.$confirm({
        title: '提示',
        content: '确定要撤销当前信息吗？',
        okType: 'warning',
        onOk: () => {
          const formObj = {
            rgstrId: rowData.rgstrId,
            state: '1',
          };
          request.post('/bis/insp/gnrl', formObj).then((res) => {
            if (res.success) {
              this.addShuiKuSuccess();
              this.$message.success('提交成功');
            } else {
              this.cancelHandler();
            }
          });
        },
      });
    },
  },
};
</script>

<style lang='less' scoped>
@import url('../../assets/style/tableScroll1.less');
#dxdcListMainsk {
  overflow-y: hidden;
}
</style>
