<!-- 土壤污染 -->
<template>
  <!-- 自定义表单 -->
  <BasicForm @register="registerForm">
    <template #trwr="{ model }">
      <div class="ml-5 flex">
        <div class="mr-6">超过土壤污染风险管控标准</div>
        <!-- 单选的时候，复选不禁用； 复选的时候，单选不选中-->
        <!-- dclx是2，是否未标准地块(sfwrdk是1)，筛选值、管制值、未超出 这3个不能选择，并且wrwYjwSxz及wrwYjwGzz清空 -->
        <a-checkbox v-model:checked="model['cbSxz']" value="筛选值" :disabled="isDisabled" @change="checkboxChanged(model)">筛选值</a-checkbox>
        <a-checkbox v-model:checked="model['cbGzz']" :disabled="isDisabled" value="管制值" @change="checkboxChanged(model)">管制值</a-checkbox>
        <a-radio v-model:checked="model['wcc']" value="未超出" :disabled="isDisabled" @change="radioChanged(model)">未超出</a-radio>
      </div>
    </template>
    <template #wrwSxz="{ 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">
            <a-checkbox-group v-model:value="previousValues[field + index]" @change="(val) => onChangeSxz(val, model, field + index)">
              <a-checkbox :value="item" v-for="(item, cIndex) in oList[key]" :key="cIndex" :disabled="allgz?.includes(item)">
                {{ item }}
              </a-checkbox>
            </a-checkbox-group>
          </div>
        </div>
      </div>
    </template>
    <template #wrwGzz="{ 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">
            <a-checkbox-group v-model:value="previousValues[field + index]" @change="(val) => onChangeGzz(val, model, field + index)">
              <a-checkbox :value="item" v-for="(item, cIndex) in oList[key]" :key="cIndex" :disabled="allSX?.includes(item)">
                {{ item }}
              </a-checkbox>
            </a-checkbox-group>
          </div>
        </div>
      </div>
    </template>
    <template #cbqymj="{ model, field }">
      <a-input-number v-model:value="model[field]" />
    </template>
  </BasicForm>
</template>

<script lang="ts" setup>
  //引入依赖
  import { ref, nextTick, watch, toRaw } from 'vue';
  import { useForm, BasicForm, FormSchema } from '/@/components/Form';

  const oList = ref({
    有机物: ['六六六', '滴滴涕', '多氯联苯', '二噁英', '其他POPs', '有机物其他'],
    重金属: ['镉', '铬', '砷', '铅', '汞', '重金属其他'],
  });
  const wrwYjwSxz = ref([]); // 例如：["六六六", "滴滴涕", "镉", "铬"]
  const wrwYjwGzz = ref([]); // 例如：["铅", "汞", "多氯联苯"]

  const wrwZjsSxz = ref([]);
  const wrwZjsGzz = ref([]);
  const allSX = ref([]);
  const allgz = ref([]);
  // 例如：{ "wrwYjwSxz0": [ "六六六", "滴滴涕" ], "wrwYjwSxz1": [ "镉", "铬" ], "wrwYjwGzz1": [ "铅", "汞" ], "wrwYjwGzz0": [ "多氯联苯" ] }
  let previousValues = ref({
    wrwYjwSxz0: [],
    wrwYjwSxz1: [],
    wrwYjwGzz0: [],
    wrwYjwGzz1: [],
  });
  const props = defineProps({
    labelFirst: {
      type: String,
      default: '初步',
    },
    data: {
      type: Object,
      default: {},
    },
    dclx: {
      type: Number,
    },
    sfwrdk: {
      type: String,
    },
    isRead: {
      type: Boolean,
      default: 0,
    },
  });
  // Emits声明
  const emit = defineEmits(['gettrMj']);
  //
  const checkboxChanged = (model) => {
    if (model.cbSxz || model.cbGzz) {
      model.wcc = false;
      updateSchema({
        label: '土壤污染物超标区域面积(m²)',
        field: 'cbqymj',
        component: 'InputNumber',
        required: true,
        slot: 'cbqymj',
        ifShow: ({ values }) => {
          console.log(values, 'values');
          let flg = true;
          if (!values.wcc) {
            flg = true;
          } else {
            if (values.cbGzz || values.cbSxz) {
              flg = true;
            } else {
              flg = false;
            }
          }

          return flg;
        },
        componentProps: ({ formModel, formActionType }) => {
          return {
            onchange: () => {
              emit('gettrMj', formModel.cbqymj);
            },
          };
        },
        //
      });
    } else {
      updateSchema({
        label: '土壤污染物超标区域面积(m²)',
        field: 'cbqymj',
        component: 'InputNumber',
        required: false,
        slot: 'cbqymj',
        ifShow: ({ values }) => {
          console.log(values, 'values');
          let flg = true;
          if (!values.wcc) {
            flg = true;
          } else {
            if (values.cbGzz || values.cbSxz) {
              flg = true;
            } else {
              flg = false;
            }
          }

          return flg;
        },
        componentProps: ({ formModel, formActionType }) => {
          return {
            onchange: () => {
              emit('gettrMj', formModel.cbqymj);
            },
          };
        },
        //
      });
    }
  };

  const radioChanged = (model) => {
    if (model.wcc) {
      model.cbSxz = false;
      model.cbGzz = false;
      model.cbqymj = 0; // 土壤污染物超标区域面积变为0
    }
  };
  //自定义表单字段
  const formSchemas: FormSchema[] = [
    {
      label: '污染地块id',
      field: 'wrdkid',
      component: 'Input',
      show: false,
    },
    {
      label: 'id',
      field: 'id',
      component: 'Input',
      show: false,
    },
    {
      label: '超出筛选值',
      field: 'cbSxz',
      component: 'RadioGroup',
      show: false,
    },
    {
      label: '超出管制值',
      field: 'cbGzz',
      component: 'RadioGroup',
      show: false,
    },
    {
      label: '未超出',
      field: 'wcc',
      defaultValue: 3,
      component: 'RadioGroup',
      show: false,
    },
    {
      label: '土壤受污染程度',
      field: 'wrcd',

      component: 'RadioGroup',
      slot: 'trwr',
    },

    {
      label: '土壤污染物超标区域面积(m²)',
      field: 'cbqymj',
      component: 'InputNumber',
      slot: 'cbqymj',
      ifShow: ({ values }) => {
        console.log(values, 'values');
        let flg = true;
        if (!values.wcc) {
          flg = true;
        } else {
          if (values.cbGzz || values.cbSxz) {
            flg = true;
          } else {
            flg = false;
          }
        }

        return flg;
      },
      componentProps: ({ formModel, formActionType }) => {
        return {
          onchange: () => {
            emit('gettrMj', formModel.cbqymj);
          },
        };
      },
      //
    },
    {
      label: '土壤超过筛选值的污染物',
      field: 'wrwYjwSxz',
      component: 'Input',
      slot: 'wrwSxz',
      colProps: { span: 24 },
      ifShow: ({ values }) => {
        let flg = true;
        if (values.cbSxz) flg = true;
        else flg = false;
        return flg;
      },
    },
    {
      label: '筛选值',
      field: 'wrwZjsSxz',
      show: false,
      component: 'RadioGroup',
    },
    {
      label: '土壤超过管制值的污染物',
      field: 'wrwYjwGzz',
      component: 'Input',
      slot: 'wrwGzz',
      colProps: { span: 24 },
      ifShow: ({ values }) => {
        let flg = true;
        if (values.cbGzz) flg = true;
        else flg = false;
        return flg;
      },
    },
    {
      label: '管制值',
      field: 'wrwZjsGzz',
      show: false,
      component: 'RadioGroup',
    },
    {
      label: '地下水是否污染',
      field: 'sfWr',
      defaultValue: 0,
      component: 'RadioGroup',
      required: true,
      componentProps: {
        options: [
          { label: '否', value: 0 },
          { label: '是', value: 1 },
        ],
      },
    },
    {
      label: '地下水是否作为饮用水源',
      field: 'sfYysy',
      defaultValue: 0,
      component: 'RadioGroup',
      required: true,
      componentProps: {
        options: [
          { label: '否', value: 0 },
          { label: '是', value: 1 },
        ],
      },
    },
  ];

  const [registerForm, { getFieldsValue, setFieldsValue, validate, updateSchema }] = useForm({
    //注册表单列
    schemas: formSchemas,
    //不显示查询和重置按钮
    showActionButtonGroup: false,
    //默认row行配置,当 layout 为 horizontal 生效
    rowProps: { gutter: 24, justify: 'start', align: 'middle' },
    //全局col列占比(每列显示多少位)，和schemas中的colProps属性一致
    baseColProps: { span: 12 },
    //使用labelCol的样式参数来控制标题宽度
    labelCol: { style: { width: '250px' } },
    //row行的样式
    baseRowStyle: { width: '100%' },
    //表单布局属性，支持（vertical,horizontal），默认为horizontal
    layout: 'horizontal',
  });
  // 筛选之
  const onChangeSxz = (val, model, field) => {
    console.log(val, model, field, '222');
    allSX.value = [];
    const newValues = Array.from(val);
    previousValues.value[field] = newValues;
    // 筛选值有机物
    wrwYjwSxz.value = previousValues.value.wrwYjwSxz0;
    // 筛选值重金属
    wrwZjsSxz.value = previousValues.value.wrwYjwSxz1;

    allSX.value = [...wrwYjwSxz.value, ...wrwZjsSxz.value];

    model.wrwYjwSxz = wrwYjwSxz.value.join(',');
    model.wrwZjsSxz = wrwZjsSxz.value.join(',');
  };
  const onChangeGzz = (val, model, field) => {
    console.log(val, model, field, '333');
    allgz.value = [];
    const newValues = Array.from(val);
    previousValues.value[field] = newValues;
    // 管制值有机物
    wrwYjwGzz.value = previousValues.value.wrwYjwGzz0;
    // 管制值重金属
    wrwZjsGzz.value = previousValues.value.wrwYjwGzz1;

    allgz.value = [...wrwYjwGzz.value, ...wrwZjsGzz.value];

    model.wrwYjwGzz = wrwYjwGzz.value.join(',');
    model.wrwZjsGzz = wrwZjsGzz.value.join(',');
  };
  const isDisabled = ref(false);
  // const onPropsChange = ([dclxValue, sfwrdkValue]) => {
  //   console.log(dclxValue, sfwrdkValue, '2222');
  //   if (dclxValue === '2' && sfwrdkValue === '1') {
  //     isDisabled.value = true;
  //   } else {
  //     isDisabled.value = false;
  //   }

  //   wrwYjwSxz.value = [];
  //   wrwZjsSxz.value = [];
  //   wrwYjwGzz.value = [];
  //   wrwZjsGzz.value = [];
  // };
  // watch(() => [props.dclx, props.sfwrdk], onPropsChange, { deep: true });
  watch(
    () => [props.data, props.isRead],
    async ([val, val1]) => {
      val &&
        nextTick(async () => {
          const obj: any = toRaw(val);
          obj.cbGz = obj.cbGzz ? true : false;
          obj.cbSxz = obj.cbSxz ? true : false;
          obj.wcc = obj.wcc ? true : false;
          obj.cbGzz = obj.cbGzz ? true : false;
          if (!obj.sfWr) obj.sfWr = 0;
          if (!obj.sfYysy) obj.sfYysy = 0;
          allSX.value = [];
          // 筛选值有机物
          if (obj.wrwYjwSxz) {
            wrwYjwSxz.value = obj.wrwYjwSxz?.split(',') || [];
            allSX.value = [...wrwYjwSxz.value];
            wrwYjwSxz.value.forEach((a) => {
              if (oList.value['有机物'].includes(a)) {
                previousValues.value['wrwYjwSxz0'].push(a);
              }
            });
          }
          // 筛选值重金属
          if (obj.wrwZjsSxz) {
            wrwZjsSxz.value = obj.wrwZjsSxz?.split(',') || [];
            allSX.value = [...allSX.value, ...wrwZjsSxz.value];
            wrwZjsSxz.value.forEach((a) => {
              if (oList.value['重金属'].includes(a)) {
                previousValues.value['wrwYjwSxz1'].push(a);
              }
            });
          }
          allgz.value = [];
          // 管制值有机物
          if (obj.wrwYjwGzz) {
            wrwYjwGzz.value = obj.wrwYjwGzz?.split(',') || [];
            allgz.value = [...allgz.value, ...wrwYjwGzz.value];
            wrwYjwGzz.value.forEach((a) => {
              if (oList.value['有机物'].includes(a)) {
                previousValues.value['wrwYjwGzz0'].push(a);
              }
            });
          }
          // 管制值重金属
          if (obj.wrwZjsGzz) {
            wrwZjsGzz.value = obj.wrwZjsGzz?.split(',') || [];
            allgz.value = [...allgz.value, ...wrwZjsGzz.value];
            wrwZjsGzz.value.forEach((a) => {
              if (oList.value['重金属'].includes(a)) {
                previousValues.value['wrwYjwGzz1'].push(a);
              }
            });
          }
          updateSchema({
            label: '地下水是否污染',
            field: 'sfWr',
            defaultValue: 0,
            component: 'RadioGroup',
            required: val1 ? true : false,
            componentProps: {
              options: [
                { label: '否', value: 0 },
                { label: '是', value: 1 },
              ],
            },
          });
          updateSchema({
            label: '地下水是否作为饮用水源',
            field: 'sfYysy',
            defaultValue: 0,
            component: 'RadioGroup',
            required: val1 ? true : false,
            componentProps: {
              options: [
                { label: '否', value: 0 },
                { label: '是', value: 1 },
              ],
            },
          });
          await setFieldsValue({
            ...val,
          });
        });
    },
    { deep: true, immediate: true }
  );
  //
  // 获取子组件 列表
  async function getFormValueTr() {
    //获取所有值
    let fieldsValue = await getFieldsValue();
    fieldsValue = await validate();

    fieldsValue.cbGz = fieldsValue.cbGzz ? 1 : 0;
    fieldsValue.cbSxz = fieldsValue.cbSxz ? 1 : 0;
    fieldsValue.wcc = fieldsValue.wcc ? 1 : 0;
    fieldsValue.cbGzz = fieldsValue.cbGzz ? 1 : 0;
    console.log(fieldsValue, 'fieldsValue');

    return fieldsValue;
  }

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

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

  :deep(.ant-picker) {
    width: 100%;
  }

  :deep(.ant-form-item-label) {
    height: fit-content;
  }
</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: 100px;
        border-right: 1px solid #e6e6e6;
      }
    }

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