﻿<template>
  <div id="" style="width: 100%;height: 100%;">
    <a-layout>
      <a-layout-sider
        :style="{
          'max-height': testHeight + 'px',
          height: testHeight + 'px',
        }"
        style="overflow: auto;">
        <a-tree
          :tree-data="leftTreeData"
          :selected-keys="selectedKeys"
          :replace-fields="{children: 'children', title: 'name', key: 'id'}"
          @select="onSelect"
        />
      </a-layout-sider>
      <a-layout>
        <a-layout-header>
          <a-form layout="inline" :model="formInline">
            <a-form-item v-for="item in formModelData" :key="item.id" :label="item.name">
              <a-input v-if="item.type == '1'" v-model:value="formInline[item.id]" :placeholder="`请输入${item.name}`" style="width: 150px;" allow-clear></a-input>
              <a-input-number
                v-if="item.type == '2'"
                id="inputNumber"
                v-model:value="formInline[item.id]"
                :placeholder="`请输入${item.name}`"
                style="width: 150px;"
                allow-clear />
              <a-select v-if="item.type == '3'" v-model:value="formInline[item.id]" allow-clear style="width: 150px;">
                <a-select-option v-for="select in selectCollection[item.id]" :key="select.id" :value="select.content">{{ select.content }}</a-select-option>
              </a-select>
              <a-range-picker v-if="item.type == '4'" v-model:value="formInline[item.id]" value-format="YYYY-MM-DD" format="YYYY-MM-DD" style="width: 150px;"/>
              <a-select
                v-if="item.type == '5'"
                v-model:value="formInline[item.id]"
                allow-clear
                mode="multiple"
                :filter-option="filterOption"
                :max-tag-count="1"
                style="width: 180px;">
                <a-select-option v-for="select in selectCollection[item.id]" :key="select.id" :value="select.content">{{ select.content }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="searchList">查询</a-button>
            </a-form-item>
            <a-form-item>
              <!-- /modular-source/6ace62b8e2bb467d98286d260aebcef2 -->
              <a-upload
                name="file"
                :multiple="false"
                action="/modular-source/6ace62b8e2bb467d98286d260aebcef2/pdcApi/bis/insp/BisDynamicModelData/importDynamicModelData"
                :data="{ tabId: selectedKeys[0] }"
                :accept="'.xls,.xlsx'"
                :headers="header"
                @change="handleChange"
                :show-upload-list="false">
                <a-button type="primary">批量导入</a-button>
              </a-upload>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="exportTable">导出</a-button>
            </a-form-item>
          </a-form>
        </a-layout-header>
        <a-layout-content :style="{ height: tableHeight + 'px' }">
          <a-table
            row-key="pid"
            :columns="columns"
            :data-source="tableData"
            :loading="tableLoading"
            bordered
            :pagination="false"
            :scroll="{ x: true, y: tableHeight - 60 }"
            :style="{ height: tableHeight + 'px' }"
            style="width: 100%;">
            <template #bodyCell="{ column, record, text, index }">
              <template v-if="column.slots?.customRender === 'tooltipCell'">
                <a-tooltip placement="topLeft" :title="text">
                  <span>{{ text }}</span>
                </a-tooltip>
              </template>
              <template v-else-if="column.dataIndex === 'index'">
                {{ (pageNum - 1) * pageSize + index + 1 }}
              </template>
              <template v-else-if="column.dataIndex === 'action'">
                <a-button type="link" @click="getFilling(record)">填报</a-button>
              </template>
            </template>
          </a-table>
          <a-pagination
            show-size-changer
            :pageSize="pageSize"
            @update:pageSize="pageSize = $event"
            :total="total"
            :page-size-options="['1', '2', '3', '4', '10']"
            :show-total="total => `共${total}条`"
            @showSizeChange="handleSizeChange"
            @change="handleCurrentChange"
            style="margin-top: 10px;" />
        </a-layout-content>
      </a-layout>
    </a-layout>

    <a-modal
      :open="fillingFlag"
      :title="`${fillingName}工程`"
      width="50%"
      okText="保存"
      @ok="submitFilling"
      @cancel="fillingFlag = false">
      <a-form :model="fillingFormModel" :label-col="{span: 6}" :wrapper-col="{span: 16}" :rules="fillingRules" ref="fillingRef">
        <a-spin :spinning="modelLoading">
          <a-form-item v-for="item in fillingData" :key="item.id" :label="item.name" :required="item.required == '1'" :prop="item.id">
            <a-input v-if="item.type == '1'" v-model:value="fillingFormModel[item.id]" :placeholder="`请输入${item.name}`" allow-clear :disabled="item.disabled == '1'"></a-input>
            <a-input-number
              v-if="item.type == '2'"
              id="inputNumber"
              v-model:value="fillingFormModel[item.id]"
              :placeholder="`请输入${item.name}`"
              allow-clear
              :disabled="item.disabled == '1'"/>
            <a-select v-if="item.type == '3'" v-model:value="fillingFormModel[item.id]" allow-clear :disabled="item.disabled == '1'">
              <a-select-option v-for="select in selectCollection[item.id]" :key="select.id" :value="select.content">{{ select.content }}</a-select-option>
            </a-select>
            <a-range-picker v-if="item.type == '4'" v-model:value="fillingFormModel[item.id]" value-format="YYYY-MM-DD" format="YYYY-MM-DD" :disabled="item.disabled == '1'"/>
            <a-select
              v-if="item.type == '5'"
              v-model:value="fillingFormModel[item.id]"
              allow-clear
              mode="multiple"
              :filter-option="filterOption"
              :max-tag-count="1"
              :disabled="item.disabled == '1'">
              <a-select-option v-for="select in selectCollection[item.id]" :key="select.id" :value="select.content">{{ select.content }}</a-select-option>
            </a-select>
            <a-cascader
              v-if="item.type == '6'"
              v-model="fillingFormModel[item.id]"
              :options="selectOption[item.id]"
              :field-names="{label: 'content', value: 'content', children: 'children'}"
              allow-clear
              placeholder="请选择"
              :disabled="item.disabled == '1'"/>
          </a-form-item>
        </a-spin>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import moment from 'moment';
import { h } from 'vue';
import request from '../../utils/gw_ajax_request';
import { exportModel } from '../../utils/gw_exportModel';

export default {
  data() {
    return {
      moment,
      testHeight: window.innerHeight - 130,
      tableHeight: window.innerHeight - 280,
      leftTreeData: [],
      selectedKeys: [],
      formModelData: [],
      formInline: {},
      selectCollection: {}, // 下拉框集合
      tableColumnsData: [], // 表格列集合
      columns: [],
      tableData: [],
      tableLoading: false,
      pageNum: 1,
      pageSize: 10,
      total: 0,
      header: {
        persId: localStorage.getItem('persId'),
        accessToken: localStorage.getItem('accessToken'),
        orgId: localStorage.getItem('orgId'),
      },
      fillingName: '',
      fillingFlag: false,
      fillingFormModel: {},
      fillingRules: {},
      fillingData: [],
      selectOption: {},
      modelLoading: true,
      pid: '',
    };
  },
  created() {
    this.searchNameTable();
  },
  methods: {
    // 获取左侧树形列表
    searchNameTable() {
      request
        .post('/bis/insp/BisDynamicModelTab/getTabList', {})
        .then((res) => {
          if (res.success) {
            this.leftTreeData = res.data;
            this.selectedKeys = [res.data[0].id];
            this.getFormModelData();
          } else {
            this.$message.error(res.message);
          }
        });
    },
    // 点击树形选取
    onSelect(selectedKeys, info) {
      this.pageNum = 1;
      this.pageSize = 10;
      this.selectedKeys =
        selectedKeys.length == 0 ? [this.leftTreeData[0].id] : selectedKeys;
      this.formInline = {};
      this.getFormModelData();
    },
    // 获取筛选框数据和获取表格列的值
    getFormModelData() {
      this.tableLoading = true;
      const params = {
        tabId: this.selectedKeys[0],
        // filterBox: '1'
      };
      this.selectCollection = {};
      this.formModelData = [];
      this.tableColumnsData = [];
      this.columns = [];
      request
        .post('/bis/insp/BisDynamicModelField/getFieldList', params)
        .then((res) => {
          this.searchList();
          if (res.success) {
            this.columns.push({
              title: '序号',
              width: 60,
              align: 'center',
              dataIndex: 'index',
            });
            res.data.forEach((item) => {
              if (item.filterBox == '1') {
                this.formModelData.push(item);
              }
              if (item.type == '3' || item.type == '5') {
                this.getSelectCollection(item.id);
              }
              if (item.stat == '1') {
                this.tableColumnsData.push(item);
                this.columns.push({
                  title: item.name,
                  key: item.id,
                  dataIndex: item.id,
                  ellipsis: true,
                  align: 'center',
                  width: 150,
                  slots: { customRender: 'tooltipCell' },
                  customCell: () => {
                    return {
                      style: {
                        maxWidth: '150px',
                        overflow: 'hidden',
                        whiteSpace: 'nowrap',
                        textOverflow: 'ellipsis',
                      },
                    };
                  },
                });
              }
              if (item.required == '1') {
                this.fillingRules[item.id] = [
                  {
                    required: true,
                    message: `${item.name}为必填项`,
                    trigger: 'change',
                  },
                ];
              }
            });
            this.columns.push({
              title: '操作',
              dataIndex: 'action',
              align: 'center',
              width: 100,
            });
          } else {
            this.$message.error(res.message);
          }
        });
    },
    getSelectCollection(id) {
      const params = {
        fieldId: id,
      };
      request
        .post('/bis/insp/BisDynamicModelComboBox/getList', params)
        .then((res) => {
          this.$set(this.selectCollection, id, res.data);
        });
    },
    searchList() {
      const paramMap = {};
      Object.keys(this.formInline).forEach((item) => {
        if (Array.isArray(this.formInline[item])) {
          paramMap[item] = this.formInline[item].join(',');
        } else {
          paramMap[item] = this.formInline[item];
        }
      });

      const { pageNum, pageSize } = this;

      const params = {
        tabId: this.selectedKeys[0],
        paramMap,
        pageNum,
        pageSize,
      };

      request
        .post('/bis/insp/BisDynamicModelData/getList', params)
        .then((res) => {
          if (res.success) {
            this.tableLoading = false;
            this.tableData = res.data.list;
            this.total = res.data.total;
          } else {
            this.$message.error(res.message);
          }
        });
    },
    filterOption(input, option) {
      // 筛选条件
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    // 几条一页
    handleSizeChange(size, val) {
      this.pageSize = val;
      this.searchList();
    },
    // 下一页
    handleCurrentChange(val) {
      this.pageNum = val;
      this.searchList();
    },
    // 导出
    async exportTable() {
      const paramMap = {};
      Object.keys(this.formInline).forEach((item) => {
        if (Array.isArray(this.formInline[item])) {
          paramMap[item] = this.formInline[item].join(',');
        } else {
          paramMap[item] = this.formInline[item];
        }
      });

      const params = {
        tabId: this.selectedKeys[0],
        paramMap,
      };

      const name = this.leftTreeData.filter(
        (item) => item.id == this.selectedKeys[0],
      )[0].name;
      const data = JSON.stringify(params);
      const url = '/pdcApi/bis/insp/BisDynamicModelData/exportDynamicModelData'; // '/modular-source/6ace62b8e2bb467d98286d260aebcef2'
      const type = 'post';
      const exportName = `${name}督查对象基础信息.xls`;
      const result = await exportModel(type, url, exportName, data);
    },
    // 导入
    handleChange(info) {
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          this.$message.success(`${info.file.name} 导入成功!`);
          this.getFormModelData();
        } else {
          this.$message.error(info.file.response.message);
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 导入失败!`);
      }
    },
    getFilling(row) {
      this.pid = row.pid;
      this.fillingData = [];
      this.fillingFlag = true;
      this.modelLoading = true;
      const nameId = this.tableColumnsData.filter(
        (item) => item.name == '对象名称',
      )[0].id;
      this.fillingName = row[nameId];
      const params = {
        tabId: this.selectedKeys[0],
        pid: row.pid,
      };
      request
        .post('/bis/insp/BisDynamicModelField/getFillingFieldList', params)
        .then((res) => {
          if (res.success) {
            this.fillingData = res.data.filter((item) => item.stat == '1');
            this.fillingData.forEach((item) => {
              if (item.type == '5') {
                const typeData = item.fieldValue
                  ? item.fieldValue.split(',')
                  : null;
                this.$set(this.fillingFormModel, item.id, typeData);
              } else if (item.type == '6') {
                const typeData = item.fieldValue
                  ? item.fieldValue.split('/')
                  : null;
                this.$set(this.fillingFormModel, item.id, typeData);
              } else {
                const typeData = item.fieldValue;
                this.$set(this.fillingFormModel, item.id, typeData);
              }
              if (item.type == '3' || item.type == '5') {
                this.selectCollection[item.id] = item.comboBoxList;
              }
              if (item.type == '6') {
                this.selectOption[item.id] = item.comboBoxList;
              }
            });

            this.modelLoading = false;
          } else {
            this.$message.error(res.message);
          }
        });
    },
    submitFilling() {
      this.$refs.fillingRef.validate((valid) => {
        if (valid) {
          const paramMap = {};
          this.fillingData.forEach((item) => {
            if (item.type == '5') {
              paramMap[item.id] = this.fillingFormModel[item.id].join(',');
            } else if (item.type == '6') {
              const idData = item.id.split('/');
              idData.forEach((item1, index) => {
                paramMap[item1] = this.fillingFormModel[item.id][index];
              });
            } else {
              paramMap[item.id] = this.fillingFormModel[item.id];
            }
          });

          const params = {
            tabId: this.selectedKeys[0],
            pid: this.pid,
            paramMap,
          };
          request
            .post('/bis/insp/BisDynamicModelData/setFilling', params)
            .then((res) => {
              if (res.success) {
                this.fillingFlag = false;
                this.$message.success('保存成功！');
                this.searchList();
              } else {
                this.$message.error(res.message);
              }
            });
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style lang='less' scoped>
@import url('../../assets/style/tableScroll.less');
/deep/ .ant-layout-sider,
/deep/ .ant-layout-content,
/deep/ .ant-layout-header {
  background: #fff;
}
/deep/ .ant-layout-header {
  height: 80px;
  line-height: 80px;
  padding: 0 10px;
}
</style>
