<!-- 土壤污染 -->
<template>
  <!-- 自定义表单 -->
  <BasicForm @register="registerForm">
    <template #zyfx="{ model, field }">
      <a-radio-group v-model:value="model[field]" style="width: 100%">
        <a-radio :value="1">公众健康风险</a-radio>
        <a-radio :value="2">
          <div class="flex w-full"> <div style="width: 50px">其他</div><a-input v-model:value="model['zyfxQt']" :disabled="model[field]==2?false:true" /> </div>
        </a-radio>
      </a-radio-group>
    </template>
    <template #yjwDxs="{ model, field }">
      <div class="bd">
        <div class="row" :class="['row' + index]" v-for="(value, key, index) in oList" :key="index">
          <div class="colummn colummn0">{{ key }}</div>
          <div class="colummn colummn1" style="display: flex;width: 100%;">
            <a-checkbox-group v-model:value="previousValues[field + index]" @change="(val) => onChangeDsx(val, model, field + index)">
              <a-checkbox :value="item" v-for="(item, cIndex) in oList[key]" :key="cIndex" >
                {{ item }}
              </a-checkbox>
            </a-checkbox-group>
            <a-input placeholder="请输入其他污染物" style="width: 200px;" v-if="key == '有机物'" v-model:value="model['yjwDxsQt']" :disabled="!model['yjwWrwDxs']?.includes('有机物其他')" @change="(val) => handleQt(val, model, field, index)" />
            <a-input placeholder="请输入其他污染物" style="width: 200px;" v-if="key == '重金属'" v-model:value="model['wjwDxsQt']" :disabled="!model['wjwWrwDxs']?.includes('重金属其他')" @change="(val) => handleQt(val, model, field, index)" />
          </div>
        </div>
        <div class="row">
          <div class="colummn colummn0">是否涉及易迁移污染物</div>
          <div class="colummn colummn1">
            <a-radio-group  name="radioGroup" @change="(e) => handleRadio(e, model, 'dxs')" v-model:value="model['dxsSfsjyqywrw']">
                <a-radio value="0">否</a-radio>
                <a-radio value="1">是</a-radio>
              </a-radio-group>
          </div>
        </div>
      </div>
    </template>
    <template #dxsswrcd="{ model, field }">
      <a-radio-group  name="radioGroup" v-model:value="model[field]">
        <a-radio value="Ⅲ类">Ⅲ类</a-radio>
        <a-radio value="Ⅳ类">Ⅳ类</a-radio>
        <a-radio value="未超出">未超出</a-radio>
      </a-radio-group>
    </template>
    <template #yjwTr="{ model, field }">
      <div class="bd">
        <div class="row" :class="['row' + index]" v-for="(value, key, index) in oList" :key="index">
          <div class="colummn colummn0">{{ key }}及修复目标</div>
          <div class="colummn colummn1" style="display: flex;width: 100%;">
            <a-checkbox-group v-model:value="previousValues[field + index]" @change="(val) => onChangeTr(val, model, field + index)">
              <div v-for="(item, cIndex) in oList[key]" :key="cIndex" style="display:inline-block;">
                <a-checkbox :value="item">
                  {{ item }}  
                </a-checkbox>
                <a-select style="width: 180px;" v-model:value="previousXfmb[key=='有机物'?'trYjw':'trZjs'][item]" v-show="previousValues[field + index].includes(item) && item!='有机物其他' && item!='重金属其他'">
                    <a-select-option value="1">修复后达到一类筛选值</a-select-option>
                    <a-select-option value="0">修复后未达到一类筛选值</a-select-option>
                </a-select>
              </div>
            </a-checkbox-group>
            <div v-if="key == '有机物' && model['yjwWrwTr']?.includes('有机物其他')" class="flex">
              <a-button type="primary" :icon="h(PlusSquareTwoTone)" style="margin-right:20px;" @click="addQtList('yjw')"/>
              <div class="listBox">
                <div v-for="(item, index) in yjwqtOption" :key="index+'yjwqt'" >
                  <a-input placeholder="请输入其他污染物" style="width: 200px;" v-model:value="item['qt']" @change="(val) => handleQt(val, model, field, index)"></a-input>
                  <a-select  style="width: 180px;" v-model:value="item['lx']" >
                    <a-select-option value="1">修复后达到一类筛选值</a-select-option>
                    <a-select-option value="0">修复后未达到一类筛选值</a-select-option>
                  </a-select>
                  <a-button type="primary" danger @click="deleteQtList('yjw', index)" :disabled="yjwqtOption.length>1?false:true">删除</a-button>
                </div>
              </div>
            </div>
            <div v-if="key == '重金属' && model['wjwWrwTr']?.includes('重金属其他')" class="flex">
              <a-button type="primary" :icon="h(PlusSquareTwoTone)" style="margin-right:20px;" @click="addQtList('zjs')"/>
              <div class="listBox">
                <div v-for="(item, index) in zjsqtOption" :key="index+'yjwqt'">
                  <a-input placeholder="请输入其他污染物" style="width: 200px;" v-model:value="item['qt']" @change="(val) => handleQt(val, model, field, index)"></a-input>
                  <a-select  style="width: 180px;" v-model:value="item['lx']">
                    <a-select-option value="1">修复后达到一类筛选值</a-select-option>
                    <a-select-option value="0">修复后未达到一类筛选值</a-select-option>
                  </a-select>
                  <a-button type="primary" danger @click="deleteQtList('zjs', index)" :disabled="zjsqtOption.length>1?false:true">删除</a-button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="colummn colummn0">是否涉及易迁移污染物</div>
          <div class="colummn colummn1">
            <a-radio-group  name="radioGroup" @change="(e) => handleRadio(e, model, 'tr')" v-model:value="model['trSfsjyqywrw']">
                <a-radio value="0">否</a-radio>
                <a-radio value="1">是</a-radio>
              </a-radio-group>
          </div>
        </div>
      </div>
    </template>
  </BasicForm>
</template>

<script lang="ts" setup>
  //引入依赖
  import { ref, nextTick, watch, toRaw } from 'vue';
  import { h } from 'vue';
  import { useForm, BasicForm, FormSchema } from '/@/components/Form';
  import { PlusSquareTwoTone } from '@ant-design/icons-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  
  const { createMessage } = useMessage();
  const oList = ref({
    有机物: ['六六六', '滴滴涕', '多氯联苯', '二噁英', '其他POPs', '有机物其他'],
    重金属: ['镉', '铬', '砷', '铅', '汞', '重金属其他'],
  });
  const previousXfmb = ref({
    trYjw: {},
    trZjs: {}
  });
  const yjwTr = ref([]);
  const wjwTr = ref([]);
  const yjwDxs = ref([]);
  const wjwDxs = ref([]);

  let previousValues = ref({
    yjwTr0: [],
    yjwTr1: [],
    yjwDxs0: [],
    yjwDxs1: [],
  });

  const props = defineProps({
    labelFirst: {
      type: String,
      default: '初步',
    },
    data: {
      type: Object,
      default: {},
    },
  });

  //自定义表单字段
  const formSchemas: FormSchema[] = [
    {
      label: '污染地块id',
      field: 'wrdkid',
      component: 'Input',
      show: false,
    },
    {
      label: 'id',
      field: 'id',
      component: 'Input',
      show: false,
    },
    {
      label: '其他',
      field: 'zyfxQt',
      component: 'Input',
      show: false,
    },
    {
      label: '其他',
      field: 'Xfmb',
      component: 'Input',
      show: false,
    },

    {
      label: '需要风险管控修复土壤污染面积(m²)',
      field: 'wrmj',
      labelWidth: 200,
      // colProps: { span: 12 },
      component: 'InputNumber',
      required: true,
    },
    {
      label: '主要风险',
      field: 'zyfx',
      component: 'InputNumber',
      // colProps: { span: 12 },
      required: true,
      slot: 'zyfx',
    },
    {
      label: '风险管控、修复要求',
      colProps: { span: 24 },
      field: 'gkxflx',
      component: 'RadioGroup',
      required: true,
      componentProps: {
        options: [
          { label: '风险管控', value: 1000 },
          { label: '修复', value: 2000 },
          { label: '管控及修复', value: 3000 },
          { label: '风险可接受', value: 4000 },
        ],
      },
    },
    {
      label: '土壤是否涉及易迁移污染物',
      field: 'trSfsjyqywrw',
      component: 'RadioGroup',
      show: false,
    },
    {
      label: '地下水是否涉及易迁移污染物',
      field: 'dxsSfsjyqywrw',
      component: 'RadioGroup',
      show: false,
    },
    {
      label: '土壤风险不可接受的污染物',
      field: 'yjwTr',
      component: 'Input',
      slot: 'yjwTr',
      colProps: { span: 24 },
    },
    {
      label: '地下水是否作为饮用水源',
      field: 'dxssfzwyys',
      defaultValue: '0',
      component: 'RadioGroup',
      required: true,
      componentProps: {
        options: [
          { label: '否', value: '0' },
          { label: '是', value: '1' },
        ],
      },
    },
    {
      label: '地下水受污染程度',
      field: 'dxsswrcd',
      defaultValue: '未超出',
      component: 'RadioGroup',
      slot: 'dxsswrcd',
    },
    {
      label: '地下水污染修复区域面积(m²)',
      field: 'dxswrxfqymj',
      component: 'InputNumber',
      ifShow: ({ values }) => {
        let flg = true;
        if (values.dxsswrcd === 'Ⅲ类' || values.dxsswrcd === 'Ⅳ类') {
          flg = true;
        } else {
          flg = false;
        }

        return flg;
      },
    },
    {
      label: '地下水超过标准限值的污染物',
      field: 'yjwDxs',
      component: 'Input',
      slot: 'yjwDxs',
      colProps: { span: 24 },
      ifShow: ({ values }) => {
        let flg = true;
        if (values.dxsswrcd === 'Ⅲ类' || values.dxsswrcd === 'Ⅳ类') {
          flg = true;
        } else {
          flg = false;
        }

        return flg;
      },
    },
    {
      label: '有机物土壤其他',
      field: 'yjwTrQt',
      show: false,
      component: 'RadioGroup',
    },
    {
      label: '无机物土壤其他',
      field: 'wjwTrQt',
      show: false,
      component: 'RadioGroup',
    },
    {
      label: '有机物地下水其他',
      field: 'yjwDxsQt',
      show: false,
      component: 'RadioGroup',
    },
    {
      label: '无机物地下水其他',
      field: 'wjwDxsQt',
      show: false,
      component: 'RadioGroup',
    },


    {
      label: '无机物地下水其他',
      field: 'yjwWrwDxs',
      show: false,
      component: 'Input',
    },
    {
      label: '无机物地下水其他',
      field: 'wjwWrwDxs',
      show: false,
      component: 'Input',
    },
    {
      label: '无机物地下水其他',
      field: 'yjwWrwTr',
      show: false,
      component: 'Input',
    },
    {
      label: '无机物地下水其他',
      field: 'wjwWrwTr',
      show: false,
      component: 'Input',
    },
  ];

  const [registerForm, { getFieldsValue, setFieldsValue, resetFields, validate }] = useForm({
    //注册表单列
    schemas: formSchemas,
    rowProps: { gutter: 24, justify: 'start', align: 'middle' },
    //全局col列占比(每列显示多少位)，和schemas中的colProps属性一致
    baseColProps: { span: 12 },
    //使用labelCol的样式参数来控制标题宽度
    labelCol: { style: { width: '240px' } },
    //row行的样式
    baseRowStyle: { width: '100%' },
    //不显示查询和重置按钮
    showActionButtonGroup: false,
    layout: 'horizontal',
  });

  const zjsqtOption = ref([{qt:'',lx:''}])
  const yjwqtOption = ref([{qt:'',lx:''}])
  const addQtList = (type) => {
    if (type == 'yjw') {
      yjwqtOption.value.push({qt:'',lx:''})
    } else {
      zjsqtOption.value.push({qt:'',lx:''})
    }
  }
  const deleteQtList = (type, index) => {
    if (type == 'yjw') {
      yjwqtOption.value.splice(index,1)
    } else {
      zjsqtOption.value.splice(index,1)
    }
  }

  const onChangeDsx = (val, model, field) => {
    // console.log(val, model, field, '333');
    const newValues = Array.from(val);
    previousValues.value[field] = newValues;
    // 地下水有机物
    yjwDxs.value = previousValues.value.yjwDxs0;
    // 地下水重金属
    wjwDxs.value = previousValues.value.yjwDxs1;

    model.yjwWrwDxs = yjwDxs.value.join(',');
    model.wjwWrwDxs = wjwDxs.value.join(',');

    if (field == 'yjwDxs0' && val.indexOf('有机物其他') < 0) {
        model['yjwDxsQt'] = null
    } else if(field == 'yjwDxs1' && val.indexOf('重金属其他') < 0) {
      model['wjwDxsQt'] = null
    }
  };

  const onChangeTr = (val, model, field) => {
    console.log(val, model, field, '333');
    const newValues = Array.from(val);
    previousValues.value[field] = newValues;
    // 地下水有机物
    yjwTr.value = previousValues.value.yjwTr0;
    // 地下水重金属
    wjwTr.value = previousValues.value.yjwTr1;

    model.yjwWrwTr = yjwTr.value.join(',');
    model.wjwWrwTr = wjwTr.value.join(',');

    if (field == 'yjwTr0' && val.indexOf('有机物其他') < 0) {
        model['yjwTrQt'] = null
    } else if(field == 'yjwTr1' && val.indexOf('重金属其他') < 0) {
      model['wjwTrQt'] = null
    }
  };

  const handleQt = (e, model, field, index) =>{
    if (field == 'yjwTr'){
      if (index == 1) {
        model['wjwTrQt'] = e.target.value
      } else {
        model['yjwTrQt'] = e.target.value
      }
    } else if (field == 'yjwDxs'){
      if (index == 1) {
        model['wjwDxsQt'] = e.target.value
      } else {
        model['yjwDxsQt'] = e.target.value
      }
    }
  }

  const handleRadio = (e, model, type) => {
    if (type == 'dxs') {
      model['dxsSfsjyqywrw'] = e.target.value
    } else {
      model['trSfsjyqywrw'] = e.target.value
    }
  }

  watch(
    () => props.data,
    async (val: any) => {
      val &&
        nextTick(async () => {
          const obj: any = toRaw(val);
          // 土壤有机物
          if (obj.yjwWrwTr) {
            const yjwWrwTr = obj.yjwWrwTr?.split(',') || [];
            yjwWrwTr.forEach((a) => {
              if (oList.value['有机物'].includes(a)) {
                previousValues.value['yjwTr0'].push(a);
              }
            });
            
            previousXfmb.value.trYjw = JSON.parse(obj.trYjwXfmb)
            if (yjwWrwTr.indexOf('有机物其他') > -1) {
              yjwqtOption.value = previousXfmb.value.trYjw['有机物其他']
            }
          }
          // 土壤重金属
          if (obj.wjwWrwTr) {
            const wjwWrwTr = obj.wjwWrwTr?.split(',') || [];
            wjwWrwTr.forEach((a) => {
              if (oList.value['重金属'].includes(a)) {
                previousValues.value['yjwTr1'].push(a);
              }
            });

            previousXfmb.value.trZjs = JSON.parse(obj.trZjsXfmb)
            if (wjwWrwTr.indexOf('重金属其他') > -1) {
              zjsqtOption.value = previousXfmb.value.trZjs['重金属其他']
            }
          }

          // 地下水有机物
          if (obj.yjwWrwDxs) {
            const yjwWrwDxs = obj.yjwWrwDxs?.split(',') || [];
            yjwWrwDxs.forEach((a) => {
              if (oList.value['有机物'].includes(a)) {
                previousValues.value['yjwDxs0'].push(a);
              }
            });
          }
          // 地下水重金属
          if (obj.wjwWrwDxs) {
            const wjwWrwDxs = obj.wjwWrwDxs?.split(',') || [];
            wjwWrwDxs.forEach((a) => {
              if (oList.value['重金属'].includes(a)) {
                previousValues.value['yjwDxs1'].push(a);
              }
            });
          }
          await setFieldsValue({
            ...val,
          });
        });
    },
    { deep: true, immediate: true }
  );
  // 获取子组件 列表
  async function getFormValueTrhj() {
    console.log('子组件执行');
    //获取所有值
    let fieldsValue = await getFieldsValue();
    fieldsValue = await validate();
    //修复目标、其他必填校验
    const relusFlag = ref(true);
    if (previousValues.value.yjwTr1.length > 0) {
      let arr = previousValues.value.yjwTr1||[];
      if (zjsqtOption.value.length > 0 && arr.indexOf("重金属其他") > -1) {
        for (let i = 0; i < zjsqtOption.value.length; i++) {
          const element = zjsqtOption.value[i];
          if (!element.qt || !element.lx) {
            createMessage.warn('其他污染物名称和修复目标不能为空');
            relusFlag.value = false
            break
          }
        }
        previousXfmb.value.trZjs['重金属其他'] = zjsqtOption.value;
      }

      for (let i = 0; i < arr.length; i++) {
        const element = arr[i];
        if (element!='重金属其他' && !previousXfmb.value.trZjs[element]) {
          createMessage.warn('重金属：'+element+'修复目标未填写');
          relusFlag.value = false
          break
        }
      }
    }

    if (previousValues.value.yjwTr0.length > 0) {
      let arr = previousValues.value.yjwTr0||[];
      if (arr.indexOf("有机物其他") > -1) {
        for (let i = 0; i < yjwqtOption.value.length; i++) {
          const element = yjwqtOption.value[i];
          if (!element.qt || !element.lx) {
            createMessage.warn('其他污染物名称和修复目标不能为空');
            relusFlag.value = false
            break
          }
        }
        previousXfmb.value.trYjw['有机物其他'] = yjwqtOption.value;
      }

      for (let i = 0; i < arr.length; i++) {
        const element = arr[i];
        if (element!='有机物其他' && !previousXfmb.value.trYjw[element]) {
        createMessage.warn('有机物：'+element+'修复目标未填写');
        relusFlag.value = false
        break
        }
      }
    }
    if (!fieldsValue.zyfx) {
      createMessage.warn('主要风险信息必填');
      relusFlag.value = false
    }

    if (fieldsValue.zyfx ==2 && !fieldsValue.zyfxQt) {
      createMessage.warn('主要风险其他信息必填');
      relusFlag.value = false
    }

    fieldsValue.trZjsXfmb = JSON.stringify(previousXfmb.value.trZjs);
    fieldsValue.trYjwXfmb = JSON.stringify(previousXfmb.value.trYjw);

    return !relusFlag.value?relusFlag.value:fieldsValue;
  }

  // 通过ref必须把在父组件里面的方法导出
  defineExpose({
    getFormValueTrhj,
  });
</script>

<style scoped>
  /** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-picker) {
    width: 100%;
  }
</style>

<style lang="less" scoped>
.bd {
    border: 1px solid #e6e6e6;
    border-radius: 10px;
    // width: fit-content;

    .row {
      display: flex;

      .colummn {
        padding: 5px 10px;
      }

      .colummn0 {
        width: 150px;
        border-right: 1px solid #e6e6e6;
      }
      .colummn1 {
        flex: 1;
      }
    }

    .row0, .row1 {
      .colummn {
        border-bottom: 1px solid #e6e6e6;
      }
    }
  }
</style>
