<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="t('routes.corporation.businessAuth')"
    :cancelText="t('routes.corporation.reject')"
    :okText="t('routes.corporation.allow')"
    @cancel="closeModal"
    @visible-change="handleVisibleChange"
  >
    <template #footer>
      <div>
        <a-button type="primary" danger @click="submitModal(false)">{{
          t('routes.corporation.reject')
        }}</a-button>
        <a-button type="primary" @click="submitModal(true)">{{
          t('routes.corporation.allow')
        }}</a-button>
      </div>
    </template>
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm">
        <template #text="{ model, field }"> {{ `: ${model[field]}` }} </template>
        <template #link="{ model, field }">
          <a :href="model[field]" target="_blank">{{ `: ${model[field]}` }}</a>
        </template>
        <template #image="{ model, field }">
          <div v-if="model[field]">
            <TableImg :size="200" :simpleShow="true" :imgList="[model[field]]" />
          </div>
        </template>
      </BasicForm>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, nextTick, computed } from 'vue';
  import { TableImg } from '/@/components/Table';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { checkDevice, selectCompanyById, auditCompany } from '/@/api/corporation/modal';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useLocaleStore } from '/@/store/modules/locale';
  const localeStore = useLocaleStore();

  export default defineComponent({
    components: { BasicModal, BasicForm, TableImg },
    props: {
      userData: { type: Object },
    },
    emits: ['register'],
    setup(props) {
      const modelRef = ref({});
      const { t } = useI18n();
      const num = ref(0);
      const { createMessage } = useMessage();
      const { error, success } = createMessage; //success,
      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
      });
      const isJA = computed(() => localeStore.getLocale === 'ja');
      const handlevalidator = async (_, value) => {
        console.log('handlevalidator', value);
        if (!value) {
          return Promise.resolve();
        }
        try {
          let res = await checkDevice({
            childName: value,
          });
          if (res.message) {
            return Promise.reject(res.message);
          } else {
            return Promise.resolve();
          }
        } catch (err) {
          return Promise.reject(err);
        }
      };
      const schemas: FormSchema[] = [
        {
          field: 'name',
          label: t('routes.corporation.name'),
          slot: 'text',
          component: 'Input',
        },
        {
          field: 'contacts',
          label: '联系人',
          slot: 'text',
          component: 'Input',
        },
        {
          field: 'phone',
          label: t('routes.corporation.phone'),
          slot: 'text',
          component: 'Input',
        },
        {
          field: 'area',
          label: t('routes.corporation.area'),
          slot: 'text',
          component: 'Input',
        },
        {
          field: 'address',
          label: t('routes.corporation.address'),
          slot: 'text',
          component: 'Input',
        },
        {
          field: 'website',
          label: t('routes.corporation.website'),
          slot: 'text',
          component: 'Input',
        },
        {
          field: 'introduce',
          label: `${t('routes.corporation.introduce')} :`,
          slot: 'name',
          component: 'Input',
        },
        {
          field: 'logo',
          label: `${t('routes.corporation.companyLogo')} :`,
          slot: 'image',
          component: 'Input',
        },
        {
          field: 'qualification',
          label: `${t('routes.corporation.qualification')} :`,
          slot: 'image',
          component: 'Input',
        },
      ];
      // let schemasList = []
      const [
        registerForm,
        { setFieldsValue, resetFields, appendSchemaByField, removeSchemaByFiled },
      ] = useForm({
        labelWidth: isJA.value ? 150 : 120,
        schemas,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });
      async function submitModal(val) {
        console.log('submitModal', val);
        let res = await auditCompany({
          id: modelRef.value.id,
          state: val ? 1 : 2,
        });
        success(res);
        closeModal();
      }
      async function onDataReceive(data) {
        // 方式1;
        resetFields();
        let { id } = data.record;
        let res = await selectCompanyById({
          id,
        });
        console.log('setFieldsValue', res);
        setFieldsValue({
          ...res,
        });
        modelRef.value = { ...data.record };
      }
      function numOnChange(event) {
        const value = Number(event);
        if (num.value > value) {
          //减
          let delList = Array.from(new Array(num.value)).map((_, index) => {
            console.log(index, value, num.value);
            if (index >= value) {
              return `ID${index}`;
            }
          });
          removeSchemaByFiled(delList);
          console.log('schemasList减', value, num.value, delList);
          // value,num.value,schemasList.filter((_,index) => {return !(index<num.value)}).map((_,index) => `ID${index}`))
        } else {
          //增
          let schemasList: FormSchema[] = Array.from(new Array(value)).map((_, index) => {
            return {
              field: `ID${index}`,
              component: 'Input',
              label: '设备ID' + index,
              itemProps: {
                validateTrigger: 'blur',
              },
              colProps: {
                span: 24,
              },
              rules: [
                {
                  required: false,
                  trigger: 'blur',
                  validator: handlevalidator,
                },
              ],
            };
          });
          console.log(
            'schemasList增',
            num.value,
            schemasList.filter((_, index) => {
              return index >= num.value;
            }),
          );
          schemasList
            .filter((_, index) => {
              return index >= num.value;
            })
            .forEach((item) => appendSchemaByField(item, ''));
        }
        num.value = value;
      }
      function handleVisibleChange(v) {
        v && props.userData && nextTick(() => onDataReceive(props.userData));
      }
      return {
        register,
        submitModal,
        schemas,
        registerForm,
        numOnChange,
        modelRef,
        handleVisibleChange,
        num,
        closeModal,
        errorMsg: error,
        t,
      };
    },
  });
</script>
