<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 v-if="isShowFooter">
        <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 }">
          : <span v-if="model[field]">{{ ` ${model[field]}` }}</span>
        </template>
        <template #link="{ model, field }">
          <a :href="model[field]" target="_blank">{{ `: ${model[field]}` }}</a>
        </template>
        <template #image="{ model, field }">
          <div v-if="model[field]">
            <Card style="overflow: hidden; min-height: 200px">
              <TableImg :size="200" :simpleShow="true" :imgList="[model[field]]" />
            </Card>
          </div>
        </template>
      </BasicForm>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, nextTick, computed } from 'vue';
  import { TableImg } from '/@/components/Table';
  import { Card } from 'ant-design-vue';
  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, Card },
    props: {
      userData: { type: Object },
    },
    emits: ['register', 'reload'],
    setup(props, { emit }) {
      const modelRef = ref({
        id: '',
      });
      const isShowFooter = ref(true);
      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.enterpriseName'),
          slot: 'text',
          component: 'Input',
        },
        {
          field: 'contacts',
          label: '联系人',
          slot: 'text',
          component: 'Input',
          componentProps: {
            maxLength: 20,
          },
        },
        // {
        //   field: 'companyName',
        //   label: t('routes.corporation.enterpriseName'),
        //   slot: 'text',
        //   component: 'Input',
        // },
        {
          field: 'phone',
          label: t('routes.corporation.phone'),
          slot: 'text',
          component: 'Input',
        },
        {
          field: 'area',
          label: t('routes.corporation.area'),
          slot: 'text',
          // ifShow: false,
          component: 'Input',
        },
        {
          field: 'address',
          label: t('routes.corporation.address'),
          slot: 'text',
          component: 'Input',
        },
        {
          field: 'website',
          label: t('routes.corporation.website'),
          slot: 'text',
          // ifShow: false,
          component: 'Input',
        },
        {
          field: 'introduce',
          label: `${t('routes.corporation.introduce')}`,
          slot: 'text',
          component: 'Input',
        },
        {
          field: 'logo',
          label: `${t('routes.corporation.companyLogo')} :`,
          ellipsis: true,
          slot: 'image',
          component: 'Input',
        },
        {
          field: 'qualification',
          label: `${t('routes.corporation.qualification')} :`,
          slot: 'image',
          // ifShow: false,
          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) {
        try {
          console.log('submitModal', val);
          await auditCompany({
            id: modelRef.value.id,
            state: val ? 1 : 2,
          });
          success(t('common.optSuccess'));
          closeModal();
          emit('reload');
        } catch (error) {
          console.log('error', error);
        }
      }
      async function onDataReceive(data) {
        // 方式1;
        resetFields();
        let { id, state } = data.record;
        let res = await selectCompanyById({
          id,
        });
        console.log('setFieldsValue', res);
        setFieldsValue({
          ...res,
        });
        isShowFooter.value = Number(state) === 0;
        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,
        isShowFooter,
      };
    },
  });
</script>
