<template>
  <div class="bg-[#fff] pt-6 w-full overflow-hidden">
    <BasicForm @register="registerForm">
      <template #ydlx="{ model, field }">
          <a-select
            v-model:value="model[field]"
            label-in-value
            placeholder="请选择"
            :options="options"
            allowClear
            @change="changeWrlx"
          ></a-select>
      </template>
      <template #wrdk="{ model, field }">
          <a-select
            v-model:value="model[field]"
            placeholder="请选择"
            show-search
            :options="optionsWrdk"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            :not-found-content="null"
            :field-names="{ label: 'wrdkmcid', value: 'wrdkid' }"
            @search="handleSearch"
            @change="changeWrdk"
          ></a-select>
      </template>
      <template #wrmmx="{}">
        <div class="flex">
          <a-input v-model:value="mxwrwmc" readonly placeholder="请选择" />
          <a-button type="primary" class="ml-2" @click="selectWrw">选择污染物</a-button>
          <a-button type="primary" class="ml-2" @click="count">计 算</a-button>
          <a-button type="primary" class="ml-2" @click="result">计算结果</a-button>
          <!-- <a-button type="primary" class="ml-2" @click="router.go(-1)">返回</a-button> -->
        </div>
      </template>
    </BasicForm>
    <BasicTable @register="registerTable" @fetch-success="onFetchSuccess">
      <template #tjz1="{ record }">
        <a-input v-model:value="record.tjz1" />
      </template>
      <template #tjz2="{ record }">
        <a-input v-model:value="record.tjz2" />
      </template>
      <template #bz="{ record }">
        <template v-if="!ydlx">{{ record.bz }}</template>
        <a-input v-else v-model:value="record.bz" />
      </template>
    </BasicTable>
    <!-- 选择模型 -->
    <wrwModal @register="registerModal" @success="getWrw" />
    <!-- 计算的弹框 -->
    <countModal @register="registerjstModal" />
    <!-- 点击计算结果出现的弹框 -->
    <Jsresults @register="registerjsresultModal" />
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { useForm, BasicForm } from '/@/components/Form';
  import { BasicTable } from '@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { list } from './api';
  import { useModal } from '/@/components/Modal';
  import { searchFormSchema } from './data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import wrwModal from './modal/wrwModal.vue';
  import countModal from './modal/countModal.vue';
  import Jsresults from '@/components/customComponent/Jsresults.vue';
  import { BasicColumn } from '/@/components/Table';
  import { searDkbm } from './api'

  const { createMessage } = useMessage();
  import { useRouter } from 'vue-router';
  const router = useRouter();
  const jsjgWrdkid = ref('')
  const columns: BasicColumn[] = ref([
    {
      title: '参数符号',
      dataIndex: 'csfh',
      resizable: true,
    },
    {
      title: '参数名称',
      dataIndex: 'csmc',
      resizable: true,
    },
    {
      title: '单位',
      dataIndex: 'csdw',
      resizable: true,
    },
    {
      title: '第一类用地推荐值',
      dataIndex: 'tjz1',
      resizable: true,
      slots: { customRender: 'tjz1' },
      ifShow: () => {
        return ydlx.value === '1';
      },
    },
    {
      title: '第二类用地推荐值',
      dataIndex: 'tjz2',
      resizable: true,
      slots: { customRender: 'tjz2' },
      ifShow: () => {
        return ydlx.value === '2';
      },
    },
    {
      title: '说明',
      dataIndex: 'bz',
      resizable: true,
      slots: { customRender: 'bz' },
    },
  ]);
  const changeWrlx = (val) => {
    if (val) {
      ydlx.value = val.value;
      localData.value.forEach(item => {
        if (ydlx.value === '1') {
          item.tjz = item.tjz1;
        } else if (ydlx.value === '2') {
          item.tjz = item.tjz2;
        } else {
          item.tjz = null;
        }
        updateTableDataRecord(item.id, item);
      })
    } else {
      ydlx.value = null;
    }
  };
  const changeWrdk = (val) => {
    if (val) {
      jsjgWrdkid.value = val
      params.value.wrdkid = val
    } else {
      params.value.wrdkid = null
    }
  };
  const optionsWrdk = ref([])

  const handleSearch = (val) => {
    if (!val || val.length <3) {
      return
    }
    searDkbm({wrdkbm: val}).then(res =>{
      res.forEach(element => {
        element.wrdkmcid = element.wrdkbm + '—' + element.wrdkmc
      });
      optionsWrdk.value = res
    })
  }
  async function onFetchSuccess(result) {
    localData.value = JSON.parse(JSON.stringify(result.items));
  }
  const localData = ref([]);
  //注册table数据
  const [registerModal, { openModal }] = useModal();
  const [registerjsresultModal, { openModal: openjsresultModal }] = useModal();
  const [registerjstModal, { openModal: openjsModal }] = useModal();

  const [registerForm, { validate }] = useForm({
    //注册表单列
    schemas: searchFormSchema,
    //不显示查询和重置按钮
    showActionButtonGroup: false,
    //默认row行配置,当 layout 为 horizontal 生效
    rowProps: { gutter: 24, justify: 'start', align: 'middle' },
    //全局col列占比(每列显示多少位)，和schemas中的colProps属性一致
    baseColProps: { span: 12 },
    //使用labelCol的样式参数来控制标题宽度
    labelCol: { style: { width: '100px' } },
    //row行的样式
    baseRowStyle: { width: '100%' },
  });
  const { tableContext } = useListPage({
    tableProps: {
      title: '',
      api: list,
      beforeFetch: async (params) => {
        params.ydlx = ydlx.value;
        params.wrdkid = '';
        params.pageNo = 1;
        params.pageSize = 100;
      },
      columns: columns,
      canResize: false,
      showIndexColumn: true,
      showActionColumn: false,
      useSearchForm: false,
      actionColumn: {
        width: 120,
        fixed: 'right',
      },
      pagination: false,
    },
  });
  const [registerTable, { reload, getDataSource, updateTableDataRecord }, {}] = tableContext;
  const mxwrwmc = ref();
  const ydlx = ref();
  const params = ref<any>({
    mxwrwId: '',
    ydlx: '',
    wrdkid: '',
    tj: ''
  });
  const options = ref([
    {
      label: '一类用地',
      value: '1',
    },
    {
      label: '二类用地',
      value: '2',
    },
  ]);
  // 选择污染物
  function selectWrw() {
    openModal(true, {
      record: {},
      isUpdate: true,
      showFooter: true,
    });
  }
  // 获取污染物
  async function getWrw(v) {
    console.log(v, 'v');
    mxwrwmc.value = v[0].wrwmc;
    params.value.mxwrwId = v[0].id;
  }
  function checkItem(item, index, ydlxValue) {
    const tjzField = ydlxValue === '1' ? 'tjz1' : 'tjz2';
    const bzField = item.bz;
    if ((item.tjz !== item[tjzField]) && (bzField === '' || bzField === null)) {
      createMessage.warn(`第${index + 1}行的说明是必填项`);
      return false;
    }
    return true;
  }
  // 计算
  async function count() {
    let values = await validate();
    // console.log(values, '结果数据')
    if (!values.wrdkid) {
      createMessage.warn('请选择地块编码');
      return;
    }
    if (!values.ydlx) {
      createMessage.warn('请选择用地类型');
      return;
    }
    if (!params.value.mxwrwId) {
      createMessage.warn('请选择污染物');
      return;
    }
    // 用地推荐值是否进行了改变
    params.value.ydlx = values.ydlx.value;
    params.value.tj = (values.tj && values.tj.length > 0)?values.tj.split(","):[];
    params.value.csList = getDataSource();
    const allItemsValid = params.value.csList.every((item, index) => {
      return checkItem(item, index, ydlx.value);
    });
    if (!allItemsValid) {
      return;
    }

    // console.log(params.value)
    // return
    openjsModal(true, {
      record: params.value,
      isUpdate: true,
      showFooter: true,
    });
  }
  // 计算结果
  async function result() {
    openjsresultModal(true, { record: {}, isUpdate: true, showFooter: false });
  }
</script>
