<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 layout="inline">
            <a-form-item label="对象名称">
              <a-input
                v-model:value="searchNameOfSzName"
                placeholder="请输入对象名称"
                allow-clear
              />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="refreshCurrentShow">
                查询
              </a-button>
              <!-- <a-button
                type="primary"
                @click="toAddNewObj"
                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 }">
              <span v-if="column.dataIndex === 'action' && ownPriv('manage')">
                <a @click="deleteHandler(record)">删除</a>
              </span>
            </template>
          </a-table>
        </div>
      </a-layout-content>
    </a-layout>
    <a-modal
      title="添加对象"
      v-model:open="addObjDialogVisible"
      @ok="addNewJcObj('formObj')"
      @cancel="addObjDialogVisible = false"
      width="50%"
    >
      <a-form
        :model="formObj"
        ref="formObj"
        :label-col="{ span: 4 }"
        style="max-width:100%"
      >
        <a-form-item label="水源名称" required>
          <a-input v-model:value="formObj.nm" 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.loc" autocomplete="off" />
        </a-form-item>
        <a-form-item label="计划完工时间">
          <a-date-picker v-model:value="formObj.planCpmTm" placeholder="选择日期" />
        </a-form-item>
        <a-form-item label="主要建设内容" required>
          <a-textarea v-model:value="formObj.buldNote" autocomplete="off" />
        </a-form-item>
        <a-form-item label="总投资（万元）" required>
          <a-input v-model:value="formObj.cost" autocomplete="off" />
        </a-form-item>
        <a-form-item label="完成投资（万元）" required>
          <a-input v-model:value="formObj.comCost" autocomplete="off" />
        </a-form-item>
        <a-form-item label="工程建设进展" required>
          <a-textarea v-model:value="formObj.prjPrsg" autocomplete="off" />
        </a-form-item>
        <a-form-item label="经度">
          <a-input v-model:value="formObj.centerX" autocomplete="off" />
        </a-form-item>
        <a-form-item label="纬度">
          <a-input v-model:value="formObj.centerY" autocomplete="off" />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-modal>
</template>

<script>
import { getSupObjListNotInspGroupId } from '../../api/duChaPlan';
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'],
  data() {
    return {
      addOnce: false,
      searchNameOfSzName: '',
      searchNameOfAdName: '',
      searchNameOfwtdstNm: '',
      rsAdmDep: '',
      type: '',
      wtdstState: '',
      engLevel: '',
      wtdstType: '',
      stnm: '',
      pageIndex: 1,
      pageSize: 10,
      total: 0,
      currentShowList: [],
      dialogFormVisible: false,
      formLabelWidth: '120',
      addArr: '',
      addName: '',
      addLttd: '',
      addLgtd: '',
      multipleSelection: [],
      gongchengguimo: [
        {
          value: '类型一',
          label: '类型一',
        },
        {
          value: '类型二',
          label: '类型二',
        },
      ],
      searchProvTreeListCode: '',
      qyDataList: [],
      loading: false,
      showLeftTree: true,
      addObjDialogVisible: false,
      formObj: {
        name: '',
        lyjgName: '',
        rsLoc: '',
        location: '',
        intm: '',
        type: '',
        regCode: '',
        centerX: '',
        centerY: '',
        intm: '',
        adCode: '',
      },
      currentAdCode: '',
      props: {
        value: 'id',
        label: 'label',
        children: 'cities',
      },
      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: 'adFullName',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          ellipsis: true,
        },
      ],
    };
  },
  components: {
    provTreeListQy,
    provTreeList,
  },
  watch: {
    dczId: function (n, o) {
      this.searchProvTreeListCode = '';
    },
    qyDataList(n, o) {
      if (this.qyDataList.length == 0) {
        this.showLeftTree = false;
      } else {
        this.showLeftTree = true;
      }
      console.log('区域树' + n.length + this.showLeftTree + this.objType);
      this.getTableData_jc();
    },
  },
  computed: {
    userId() {
      return localStorage.getItem('persId')
        ? localStorage.getItem('persId')
        : '1098101939614724096';
    },
  },
  mounted() {
    this.getTableData_jc();
  },
  methods: {
    showDialog() {
      this.dialogFormVisible = true;
      if (this.$refs['provTreeListQyRef']) {
        this.$refs['provTreeListQyRef'].getQyList();
      }
      this.getTableData_jc();
    },
    saveChange() {
      this.selectedRowKeys = [];
      this.addObjectChange();
    },
    treeDataEmit(item) {
      this.qyDataList = item;
      if (this.qyDataList.length == 0) {
        this.showLeftTree = false;
      } else {
        this.showLeftTree = true;
      }
    },
    getTableData_jc() {
      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,
        this.objType,
        this.searchNameOfSzName,
        '',
      ).then((res) => {
        this.loading = false;
        this.currentShowList = res.data.list;
        this.currentShowList.forEach((element, index) => {
          element['index'] = this.pageSize * (this.pageIndex - 1) + index + 1;
        });
        this.total = res.data.total;
      });
    },
    getTableData_jc1() {
      getSupObjListNotInspGroupId(
        this.searchProvTreeListCode,
        this.dczId,
        '',
        this.pageSize,
        this.pageIndex,
        this.objType,
        this.searchNameOfSzName,
        '',
      ).then((res) => {
        this.loading = false;
        this.currentShowList = res.data.list;
        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 () {
      if (this.searchProvTreeListCode) {
        this.getTableData_jc1();
      } else {
        this.getTableData_jc();
      }
    },
    toAddNewObj() {
      this.provName = '';
      this.cityName = '';
      this.countryName = '';
      for (var obj in this.formObj) {
        this.formObj[obj] = '';
      }
      this.addObjDialogVisible = true;
      this.curSelectItem = null;
      this.getAreaList();
    },
    addNewJcObj(formName) {
      if (!this.formObj.name) {
        this.$message.warning('请输入对象名称');
        return;
      }
      if (!this.formObj.type) {
        this.$message.warning('请选择项目类型');
        return;
      }

      if (!this.formObj.location) {
        this.$message.warning('请输入所在地');
        return;
      }
      this.formObj.adCode = this.currentAdCode;
      this.formObj.persId = this.userId;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          request
            .post('/supervision/plan/insertSupervisionObj', this.formObj)
            .then((res) => {
              if (res.success) {
                this.$message.success('添加成功');
                this.getTableData_jc();
                this.addObjDialogVisible = false;
                this.formObj = {
                  name: '',
                  lyjgName: '',
                  rsLoc: '',
                  location: '',
                  type: '',
                  regCode: '',
                  intm: '',
                  adCode: '',
                  centerX: '',
                  centerY: '',
                };
              } else {
                this.$message.error(res.message);
              }
            })
            .catch((res) => {
              this.$message.error('请求错误' + res.message);
            });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    editHandler(row) {
      this.formObj = row;
      this.addObjDialogVisible = true;
      this.getAreaList();
    },
    deleteHandler(row) {
      this.$confirm({
        title: '提示',
        content: '是否确认删除?',
        okType: 'warning',
        onOk: () => {
          request.get(`/tac/att/pawp/base/del/${row.id}`).then((res) => {
            if (res.success) {
              this.$message.success('删除成功');
              this.getTableData_jc();
            } else {
              this.$message.error('删除失败');
            }
          });
        },
        onCancel: () => {
          this.$message.info('已取消删除');
        },
      });
    },
    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['ptype'] = this.objType;
        obj['persId'] = this.userId;
        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) {
      this.searchProvTreeListCode = params.code;
      this.getTableData_jc1();
    },
    provTreeSelectChangeHandler_qy(params) {
      this.searchProvTreeListCode = params.code;
      this.getTableData_jc1();
    },
    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;
            }
          }
        });
    },
    provChange(val) {
      this.curSelectItem = 1;
      this.cityName = '';
      this.countryName = '';
      this.formObj.adCode = val;
      this.currentAdCode = 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.adCode = val;
        this.currentAdCode = 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.adCode = val;
        this.currentAdCode = val;
        this.countryList.forEach((ele) => {
          if (ele.adCode == this.countryName) {
            this.countryNames = ele.adName;
          }
        });
        this.formObj.location =
          this.provNames + this.cityNames + this.countryNames;
        this.formObj.adName = this.countryNames;
        this.formObj.adCode = val;
      }
    },
  },
};
</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: 28%;
}
:deep(.ant-form-item) {
  margin-bottom: 10px;
}
</style>
