<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :width="800"
    :body-style="{
      height: '400px !important',
    }"
    wrapClassName="custom-modal-box"
    :title="getTitle"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerTypeForm" />
    <div class="help-message">请先选择单位类型，再对该单位类型进行换算配置</div>
    <div class="config-title">
      <span class="font-semibold">单位换算配置</span>
      <span class="add-span" @click="addConfig" v-if="isShow">+ 增加</span>
    </div>
    <BasicForm @register="registerUnitForm" />
    <a-row
      class="row-box"
      type="flex"
      align="middle"
      v-for="(item, index) in configList"
      :key="index"
    >
      <a-col align="center" :span="2">1{{ symbolLabel }}</a-col>
      <a-col :span="1">=</a-col>
      <a-col :span="9">
        <a-input-number style="width: 100%" v-model:value="item.number" placeholder="请输入" />
      </a-col>
      <a-col :offset="1" :span="9">
        <a-select
          v-model:value="item.shiftUnitId"
          :options="standardOptions"
          :fieldNames="fieldNames"
          style="width: 100%"
          placeholder="请选择"
        />
      </a-col>
      <a-col :span="2" class="delete-span">
        <span @click="deleteConfig(index)">删除</span>
      </a-col>
    </a-row>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { FormSchema } from '/@/components/Table';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { getUnitTypeList } from '/@/api/erp/unit/type';
  import { TypeListModel } from '/@/api/erp/unit/type/model/index';
  import { UnitUpdateParamsModel } from '/@/api/erp/unit/list/model/index';
  import { getUnitListByTypeId } from '/@/api/erp/unit/list';
  import {
    addConversionList,
    updateConversionList,
    getConversionInfo,
  } from '/@/api/erp/unit/conversion';
  const { t } = useI18n();
  const unitTypeIdOptions = ref<TypeListModel[]>([]);
  const standardOptions = ref<UnitUpdateParamsModel[]>([]);
  const fieldNames = {
    label: 'name',
    value: 'id',
  };
  const isShow = ref<boolean>(false);
  const unitTypeChange = async (val, baseUnitId?) => {
    isShow.value = !!val;
    if (val) {
      standardOptions.value = await getUnitListByTypeId(val);
      updateUnitSchema([
        {
          field: 'baseUnitId',
          componentProps: {
            options: standardOptions.value,
          },
        },
      ]);
      const standardValue = standardOptions.value?.filter((x) =>
        unref(isUpdate) ? x.id === baseUnitId : x.isStandard === 1,
      )[0]?.id;
      if (standardValue) {
        setUnitFieldsValue({ baseUnitId: standardValue });
        symbolLabel.value = standardOptions.value?.filter((x) => x.id === standardValue)[0]?.name;
      }
      configList.value = [];
    }
  };

  const FormTypeSchema: FormSchema[] = [
    {
      field: 'unitTypeId',
      label: '单位类型',
      component: 'Select',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请选择单位类型',
        fieldNames,
        allowClear: false,
        onChange: unitTypeChange,
        getPopupContainer: () => document.body,
      },
    },
  ];

  const FormUnitSchema: FormSchema[] = [
    {
      field: 'baseUnitId',
      label: '基准单位',
      component: 'Select',
      required: true,
      colProps: { span: 24 },
      ifShow: () => {
        return getFieldsValue()?.unitTypeId;
      },
      componentProps: {
        placeholder: '请选择基准单位',
        fieldNames,
        onChange: (_, options) => {
          symbolLabel.value = options?.name;
        },
        getPopupContainer: () => document.body,
      },
    },
  ];

  const { notification } = useMessage();
  const isUpdate = ref(true);
  const rowId = ref('');
  const configList = ref<any>([]);

  const symbolLabel = ref<string>();
  const emit = defineEmits(['success', 'register']);

  const [registerTypeForm, { setFieldsValue, validate, getFieldsValue, updateSchema }] = useForm({
    labelWidth: 100,
    schemas: FormTypeSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });
  const [
    registerUnitForm,
    { setFieldsValue: setUnitFieldsValue, validate: validateUnit, updateSchema: updateUnitSchema },
  ] = useForm({
    labelWidth: 100,
    schemas: FormUnitSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    configList.value = [];
    isShow.value = false;
    setModalProps({ confirmLoading: false, destroyOnClose: true });

    isUpdate.value = !!data?.isUpdate;
    const info = await getUnitTypeList();
    unitTypeIdOptions.value = unref(isUpdate)
      ? info
      : info?.filter((item) => !data.existUniTypeIdList.includes(item.id));
    if (unref(isUpdate)) {
      rowId.value = data.id;
      const record = await getConversionInfo(data.id);
      setFieldsValue({
        unitTypeId: record.unitTypeId,
      });
      setUnitFieldsValue({
        baseUnitId: record.baseUnitId,
      });
      await unitTypeChange(record.unitTypeId, record.baseUnitId);

      configList.value = record.addCaseErpUnitConvertDetailDtoList;
    }
    updateSchema([{ field: 'unitTypeId', componentProps: { options: unitTypeIdOptions.value } }]);
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增单位换算' : '编辑单位换算'));

  const addConfig = () => {
    configList.value.push({ shiftUnitId: '', number: null });
  };

  const deleteConfig = (index) => {
    configList.value.splice(index, 1);
  };

  async function handleSubmit() {
    try {
      const typeValues = await validate();
      const unitValues = await validateUnit();
      const info = {
        ...typeValues,
        ...unitValues,
        addCaseErpUnitConvertDetailDtoList: configList.value,
      };
      setModalProps({ confirmLoading: true });

      if (!unref(isUpdate)) {
        await addConversionList(info);
        notification.success({
          message: '新增单位换算',
          description: t('成功'),
        });
      } else {
        info.id = rowId.value;
        await updateConversionList(info);
        notification.success({
          message: '新增单位换算',
          description: t('成功'),
        });
      }

      closeModal();
      emit('success');
    } catch (error) {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
<style lang="less" scoped>
  .help-message {
    margin: -10px 0 20px 100px;
  }

  .config-title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;

    .add-span {
      color: #5e95ff;
      cursor: pointer;
    }
  }

  .row-box {
    margin-bottom: 10px;

    .delete-span {
      text-align: center;
      color: #ff8080;
      cursor: pointer;
    }
  }
</style>
