<template>
  <a-modal
    title="添加督查对象"
    :open="dialogFormVisible"
    @ok="saveChange"
    @cancel="dialogFormVisible = false"
    width="80%"
  >
    <a-layout>
      <a-layout-sider
        width="200px"
        style="border:1px solid #d5d5ff; background: #fff;"
      >
        <p
          style="font-weight:bolder;background-color:#d5d5ff;padding:3px;margin: 0;"
        >
          <a-icon type="share-alt" />所属机构
        </p>
        <provTreeListQy
          ref="provTreeListQyRef"
          v-show="showLeftTree"
          :ddczId="dczId"
          rootCode="000000"
          rootType="1"
          style="max-height:485px;"
          @treeDataEmit="treeDataEmit"
          @provTreeSelectChange="provTreeSelectChangeHandler_qy"
        >
        </provTreeListQy>
        <provTreeList
          v-show="!showLeftTree"
          rootCode="000000"
          rootType="1"
          style="max-height:485px;"
          @provTreeSelectChange="provTreeSelectChangeHandler"
        ></provTreeList>
      </a-layout-sider>
      <a-layout-content
        style="border:1px solid #d5d5ff;margin-left:5px;padding:0px;"
      >
        <p
          style="font-weight:bolder;background-color:#d5d5ff;padding:3px;margin: 0;"
        >
          督查对象
        </p>
        <div style="padding:10px">
          <a-form :model="form" layout="inline">
            <a-form-item label="督查对象" style="display:none;">
              <a-select
                v-model:value="form.objTypeName"
                @change="selectChange"
                placeholder="请选择"
              >
                <a-select-option value="1">小水库</a-select-option>
                <a-select-option value="2">农村饮水工程</a-select-option>
                <a-select-option value="3">水毁</a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
          <a-form :model="form" layout="inline">
            <a-form-item label="工程规模">
              <a-select
                v-model:value="form.engScal"
                @change="selectChange"
                placeholder="请选择"
              >
                <a-select-option
                  v-for="item in engScalList"
                  :value="item.value"
                  :key="item.value"
                >{{ item.label }}</a-select-option
                >
              </a-select>
            </a-form-item>
            <a-form-item label="水库名称">
              <a-input
                v-model:value="form.searchNameOfRsName"
                placeholder="请输入水库名称"
                allow-clear
              />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="refreshCurrentShow">
                查询
              </a-button>
              <a-button
                type="primary"
                @click="toAddNewRsvr"
                style="margin-left: 10px;"
              >
                添加新水库
              </a-button>
            </a-form-item>
          </a-form>
          <a-table
            :row-selection="{
              selectedRowKeys: selectedRowKeys,
              onChange: handleSelectionChange,
            }"
            :columns="columns"
            :data-source="currentShowList"
            @change="handleCurrentChange"
            :loading="loading"
            rowKey="index"
            :pagination="{
              total,
              defaultPageSize: pageSize,
              showTotal: (total) => `共${total}条`,
            }"
            style="width: 100%;"
          >
            <template #bodyCell="{ column, record, text, index }">
              <template v-if="column.dataIndex === 'engScal'">
                <span v-if="record.engScal == '1'">大（1）型</span>
                <span v-else-if="record.engScal == '2'">大（2）型</span>
                <span v-else-if="record.engScal == '3'">中型</span>
                <span v-else-if="record.engScal == '4'">小（1）型</span>
                <span v-else-if="record.engScal == '5'">小（2）型</span>
                <span v-else></span>
              </template>
              <template v-if="column.dataIndex === 'rsAdmDep'">
                <span v-if="record.rsAdmDep == 1">水利部门</span>
                <span v-else-if="record.rsAdmDep == 2">电力部门</span>
                <span v-else-if="record.rsAdmDep == 3">农业部门</span>
                <span v-else-if="record.rsAdmDep == 4">林业部门</span>
                <span v-else-if="record.rsAdmDep == 5">城建部门</span>
                <span v-else-if="record.rsAdmDep == 6">航运部门</span>
                <span v-else-if="record.rsAdmDep == 7">环保部门</span>
                <span v-else>其他部门</span>
              </template>
            </template>
          </a-table>
        </div>
      </a-layout-content>
    </a-layout>
    <a-modal
      title="添加新水库"
      :open="addRsvrVisible"
      @update:open="addRsvrVisible = $event"
      @ok="addNewRsvr('formObj')"
      @cancel="addRsvrVisible = false"
      width="50%"
    >
      <a-form
        :model="formObj"
        :rules="rules"
        ref="formObj"
        :label-col="{ span: 4 }"
        style="max-width:100%"
      >
        <a-form-item label="水库名称" required>
          <a-input v-model:value="formObj.rsName" autocomplete="off" />
        </a-form-item>
        <a-form-item label="管理机构">
          <a-input v-model:value="formObj.rsAdmName" autocomplete="off" />
        </a-form-item>
        <a-form-item label="行政区域" required>
          <div>
            <a-select
              v-model:value="provName"
              @change="provChange"
              placeholder="选择省"
            >
              <a-select-option
                v-for="item in provList"
                :key="item.adCode"
                :value="item.adCode"
              >{{ item.adName }}</a-select-option
              >
            </a-select>
            <a-select
              v-model:value="cityName"
              @change="cityChange"
              placeholder="选择市"
            >
              <a-select-option
                v-for="item in cityList"
                :key="item.adCode"
                :value="item.adCode"
              >{{ item.adName }}</a-select-option
              >
            </a-select>
            <a-select
              v-model:value="countryName"
              @change="countryChange"
              placeholder="选择县"
            >
              <a-select-option
                v-for="item in countryList"
                :key="item.adCode"
                :value="item.adCode"
              >{{ item.adName }}</a-select-option
              >
            </a-select>
          </div>
        </a-form-item>
        <a-form-item label="所在地点" required>
          <a-input v-model:value="formObj.location" autocomplete="off" />
        </a-form-item>
        <a-form-item label="建成时间">
          <a-date-picker v-model:value="formObj.compDate" placeholder="选择日期" />
        </a-form-item>
        <a-form-item label="工程规模" required>
          <a-select v-model:value="formObj.engScal" placeholder="请选择">
            <a-select-option
              v-for="item in gongchengguimo"
              :key="item.value"
              :value="item.value"
            >{{ item.label }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item label="总库容(万m³)">
          <a-input v-model:value="formObj.totCap" autocomplete="off" />
        </a-form-item>
        <a-form-item label="最大坝高(m)">
          <a-input v-model:value="formObj.damSizeHig" autocomplete="off" />
        </a-form-item>
        <a-form-item label="主坝坝型">
          <a-select v-model:value="formObj.rsType" placeholder="请选择">
            <a-select-option
              v-for="item in zhubaleixing"
              :key="item.value"
              :value="item.value"
            >{{ item.label }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item label="注册登记号">
          <a-input v-model:value="formObj.regCode" autocomplete="off" />
        </a-form-item>
        <a-form-item label="经度">
          <a-input v-model:value="formObj.longitude" autocomplete="off" />
        </a-form-item>
        <a-form-item label="纬度">
          <a-input v-model:value="formObj.latitude" autocomplete="off" />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-modal>
</template>

<script>
import { getSupObjListNotInspGroupId } from '../../api/fujian_api';
import request from '../../utils/gw_ajax_request.js';
import provTreeList from '../../widgets/provTreeList.vue';
import provTreeListQy from '../../widgets/provTreeList_quyu.vue';

export default {
  props: ['dczId', 'dczName', 'plnaId', 'objType', 'pType'],
  data() {
    return {
      form: {
        engScal: '小水库',
        searchNameOfRsName: '',
      },
      addOnce: false,
      objTypeName: '小水库',
      searchNameOfRsName: '',
      searchNameOfAdName: '',
      searchNameOfwtdstNm: '',
      addLevel: '',
      rsAdmDep: '',
      engScal: '',
      wtdstState: '',
      engLevel: '',
      wtdstType: '',
      stnm: '',
      pageIndex: 1,
      pageSize: 10,
      total: 0,
      currentShowList: [],
      dialogFormVisible: false,
      formLabelWidth: '120',
      addArr: '',
      addName: '',
      addLttd: '',
      addLgtd: '',
      multipleSelection: [],
      searchProvTreeListCode: '',
      qyDataList: [],
      loading: false,
      showLeftTree: true,
      addRsvrVisible: false,
      formObj: {
        rsName: '',
        rsAdmName: '',
        rsLoc: '',
        location: '',
        intm: '',
        engScal: '',
        totCap: '',
        damMaxHigh: '',
        damTypeStr: '',
        damType: '',
        rsType: '',
        regCode: '',
        rsvrLong: '',
        rsvrLat: '',
        compDate: '',
        admDiv: '',
        longitude: '',
        latitude: '',
        centerXGd: '',
        centerYGd: '',
      },
      areasList: [],
      gongchengguimo: [],
      xskEngscale: [
        {
          value: '4',
          label: '小（1）型',
        },
        {
          value: '5',
          label: '小（2）型',
        },
      ],
      dskEngscale: [
        {
          value: '1',
          label: '大（1）型',
        },
        {
          value: '2',
          label: '大（2）型',
        },
        {
          value: '3',
          label: '中型',
        },
      ],
      zhubaleixing: [
        {
          value: '1',
          label: '混凝土坝',
        },
        {
          value: '2',
          label: '碾压混凝土坝',
        },
        {
          value: '3',
          label: '浆砌石坝',
        },
        {
          value: '4',
          label: '土坝',
        },
        {
          value: '5',
          label: '堆石坝',
        },
        {
          value: '6',
          label: '挡水坝',
        },
        {
          value: '7',
          label: '其他',
        },
      ],
      initLoacData: [
        {
          label: '江苏',
          cities: [],
        },
        {
          label: '浙江',
          cities: [],
        },
      ],
      props: {
        value: 'id',
        label: 'label',
        children: 'cities',
      },
      rules: {
        rsName: [
          { required: true, message: '请输入水库名称', trigger: 'blur' },
        ],
        rsAdmName: [
          { required: true, message: '请输入管理单位', trigger: 'blur' },
        ],
        // location: [
        //   { required: true, message: '请选择所在地', trigger: 'blur' }
        // ],
        compDate: [
          { required: true, message: '请选择完成时间', trigger: 'blur' },
        ],
      },
      provList: [],
      cityList: [],
      countryList: [],
      provName: '',
      cityName: '',
      countryName: '',
      provNames: '',
      cityNames: '',
      countryNames: '',
      curSelectItem: 0,
      selectedRowKeys: [],
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '水库名称',
          dataIndex: 'name',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '行政区划',
          dataIndex: 'location',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '工程规模',
          dataIndex: 'engScal',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '归口管理部门',
          dataIndex: 'rsAdmDep',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '总库容',
          dataIndex: 'totCap',
          align: 'center',
          ellipsis: true,
        },
      ],
    };
  },
  components: {
    provTreeListQy,
    provTreeList,
  },
  watch: {
    dczId: function (n, o) {
      this.searchProvTreeListCode = '';
    },
    objType: function (n, o) {
      this.searchProvTreeListCode = '';
      this.objType = n;
      this.getAreaList();
    },
    qyDataList(n, o) {
      if (this.qyDataList.length == 0) {
        this.showLeftTree = false;
      } else {
        this.showLeftTree = true;
      }
      this.getAreaList();
    },
    searchProvTreeListCode(val) {
      if (val) {
        this.getTableData_sk1();
      }
    },
  },
  computed: {
    userId() {
      return localStorage.getItem('persId')
        ? localStorage.getItem('persId')
        : '1098101939614724096';
    },
    engScalList() {
      return this.xskEngscale.concat(this.dskEngscale);
    },
  },
  mounted() {
    this.gongchengguimo = this.engScalList;
  },
  methods: {
    changeCurrentObjSelectName(item) {
      this.objType = item;
    },
    selectChange(val) {
      this.objType = val;
    },
    engScalFormatter(row, column) {
      if (row.engScal == 1) {
        return '大（1）型';
      } else if (row.engScal == 2) {
        return '大（2）型';
      } else if (row.engScal == 3) {
        return '中型';
      } else if (row.engScal == 4) {
        return '小（1）型';
      } else if (row.engScal == 5) {
        return '小（2）型';
      } else {
        return '';
      }
    },
    rsAdmDepFormatter(row, column) {
      return row.rsAdmDep == 1
        ? '水利部门'
        : row.rsAdmDep == 2
          ? '电力部门'
          : row.rsAdmDep == 3
            ? '农业部门'
            : row.rsAdmDep == 4
              ? '林业部门'
              : row.rsAdmDep == 5
                ? '城建部门'
                : row.rsAdmDep == 6
                  ? '航运部门'
                  : row.rsAdmDep == 7
                    ? '环保部门'
                    : '其他部门';
    },
    adNameFormatter(row, column) {
      return row.adName;
    },
    adFullNameFormatter(row, column) {
      return row.adFullName;
    },
    adCodeFormatter(row, column) {
      return row.adCode;
    },
    showDialog() {
      this.dialogFormVisible = true;
      if (this.$refs['provTreeListQyRef']) {
        this.$refs['provTreeListQyRef'].getQyList();
      }
      // this.getTableData_sk();
    },
    saveChange() {
      this.selectedRowKeys = [];
      this.addObjectChange();
    },
    treeDataEmit(item) {
      this.qyDataList = item;
      if (this.qyDataList.length == 0) {
        this.showLeftTree = false;
      } else {
        this.showLeftTree = true;
      }
    },
    getTableData_sk() {
      if (this.qyDataList.length == 0) {
        this.showLeftTree = false;
      } else {
        this.showLeftTree = true;
      }
      this.loading = true;
      var str = '';
      for (var i = 0; i < this.qyDataList.length; i++) {
        str += this.qyDataList[i].adCode + ',';
      }
      str = str.substring(0, str.length - 1);

      getSupObjListNotInspGroupId(
        str,
        this.dczId,
        '',
        this.pageSize,
        this.pageIndex,
        '24',
        this.searchNameOfRsName,
        this.engScal,
      ).then((res) => {
        this.loading = false;
        this.currentShowList = res.data.list;
        if (res.data.list && res.data.list.length) {
          this.currentShowList.forEach((element, index) => {
            element['index'] = this.pageSize * (this.pageIndex - 1) + index + 1;
          });
        }
        this.total = res.data.total;
      });
    },
    handleSelectionChange(val, row) {
      this.selectedRowKeys = val;
      this.multipleSelection = row;
    },
    handleCurrentChange(val) {
      this.pageIndex = val.current;
      this.refreshCurrentShow();
    },
    refreshCurrentShow: function () {
      this.engScal = this.form.engScal;
      this.searchNameOfRsName = this.form.searchNameOfRsName;
      if (this.objType == '24') {
        if (this.searchProvTreeListCode) {
          this.getTableData_sk1();
        } else {
          this.getTableData_sk();
        }
      }
    },
    addObjectChange: function () {
      if (this.addOnce) {
        this.addOnce = false;
        return;
      }
      this.addOnce = true;
      var objArr = [];
      const length = this.multipleSelection.length;
      for (let i = 0; i < length; i++) {
        var obj = {};
        obj['code'] = this.multipleSelection[i].code;
        obj['name'] = this.multipleSelection[i].name;
        obj['objId'] = this.multipleSelection[i].objId
          ? this.multipleSelection[i].objId
          : '';
        obj['ptype'] = '24';
        objArr.push(obj);
      }
      try {
        request
          .post('/supervision/plan/insertSupervisionObj', {
            persid: this.userId,
            nm: this.dczName,
            id: this.dczId,
            persAllAreaDtoList: [],
            persAllDtoList: [],
            persAllObjDtoList: objArr,
          })
          .then((response) => {
            if (response.success == true) {
              this.addOnce = false;
              this.dialogFormVisible = false;
              this.$message.success('添加成功');
              this.$emit('addSuccess');
            }
          });
      } catch (e) {
        alert('暂无数据');
      }
    },
    provTreeSelectChangeHandler: function (params) {
      if (!this.showLeftTree) {
        this.searchProvTreeListCode = params.code;
      }
    },
    provTreeSelectChangeHandler_qy(params) {
      this.searchProvTreeListCode = params.code;
    },
    getTableData_sk1() {
      getSupObjListNotInspGroupId(
        this.searchProvTreeListCode,
        this.dczId,
        '',
        this.pageSize,
        this.pageIndex,
        '24',
        this.searchNameOfRsName,
        this.engScal,
      ).then((res) => {
        this.loading = false;
        this.currentShowList = res.data.list;
        if (res.data.list && res.data.list.length) {
          this.currentShowList.forEach((element, index) => {
            element['index'] = this.pageSize * (this.pageIndex - 1) + index + 1;
          });
        }
        this.total = res.data.total;
      });
    },
    toAddNewRsvr() {
      this.addRsvrVisible = true;
      this.formObj.engScal = this.gongchengguimo[0].value;
      this.formObj.rsType = this.zhubaleixing[0].value;
    },
    addNewRsvr(formName) {
      if (!this.formObj.rsName) {
        this.$message.warning('请输入水库名称');
        return;
      }
      if (!this.formObj.rsAdmName) {
        this.$message.warning('请输入管理机构名称');
        return;
      }
      if (!this.formObj.location) {
        this.$message.warning('请输入所在地');
        return;
      }
      if (!this.formObj.compDate) {
        this.$message.warning('请选择建成时间');
        return;
      }
      if (!this.formObj.engScal) {
        this.$message.warning('请选择工程规模');
        return;
      }
      this.formObj.centerXGd = this.formObj.longitude;
      this.formObj.centerYGd = this.formObj.latitude;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          request
            .post('/dc/att/rsBase', this.formObj)
            .then((res) => {
              if (res.success) {
                this.$message.success('添加成功');
                this.refreshCurrentShow();
                this.addRsvrVisible = false;
                this.formObj = {
                  rsName: '',
                  rsAdmName: '',
                  rsLoc: '',
                  location: '',
                  intm: '',
                  engScal: '',
                  totCap: '',
                  damMaxHigh: '',
                  damTypeStr: '',
                  damType: '',
                  rsType: '',
                  regCode: '',
                  rsvrLong: '',
                  rsvrLat: '',
                  compDate: '',
                  admDiv: '',
                  longitude: '',
                  latitude: '',
                  centerXGd: '',
                  centerYGd: '',
                };
              } else {
                this.$message.error(res.message);
              }
            })
            .catch((res) => {
              this.$message.error('请求错误' + res.message);
            });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    getAreaList(val) {
      const areaParams = {
        adName: '',
        id: this.dczId,
        pageNum: 1,
        pageSize: 10000,
      };

      let adCode = '';
      if (!val) {
        adCode = '000000000000';
      } else {
        adCode = val;
      }
      request
        .get('/dc/ad/base/getAdData', { params: { adCode: adCode } })
        .then((res) => {
          if (res.success) {
            if (this.curSelectItem == 1) {
              this.cityList = res.data;
            } else if (this.curSelectItem == 2) {
              this.countryList = res.data;
            } else {
              this.provList = res.data;
            }
          }
        });
    },
    handleItemChange(val) {
      this.getAreaList(val);
    },
    provChange(val) {
      this.curSelectItem = 1;
      this.cityName = '';
      this.countryName = '';
      this.formObj.admDiv = val;
      this.provList.forEach((ele) => {
        if (ele.adCode == this.provName) {
          this.provNames = ele.adName;
        }
      });
      this.formObj.location = this.provNames;
      this.getAreaList(val);
    },
    cityChange(val) {
      this.curSelectItem = 2;
      if (val && val != '') {
        this.formObj.admDiv = val;
        this.countryName = '';
        this.cityList.forEach((ele) => {
          if (ele.adCode == this.cityName) {
            this.cityNames = ele.adName;
          }
        });
        this.formObj.location = this.provNames + this.cityNames;
        this.getAreaList(val);
      }
    },
    countryChange(val) {
      if (val && val != '') {
        this.formObj.admDiv = val;
        this.countryList.forEach((ele) => {
          if (ele.adCode == this.countryName) {
            this.countryNames = ele.adName;
          }
        });
        this.formObj.location =
          this.provNames + this.cityNames + this.countryNames;
      }
    },
  },
};
</script>

<style lang="less" scoped>
:deep(.ant-table-pagination) {
  float: left;
}
:deep(.ant-table-thead > tr > th),
:deep(.ant-table-tbody > tr > td) {
  padding: 0;
  height: 36px;
}
:deep(.form .ant-select) {
  width: 20%;
}
:deep(.ant-form-item) {
  margin-bottom: 10px;
}
</style>
