<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="t('routes.devices.addDevice')"
    @ok="submitModal"
    @cancel="handleCloseModal"
    @visible-change="handleVisibleChange"
  >
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm">
        <template #userName="{ model, field }">
          {{ model[field] }}
        </template>
        <template #name="{ model, field }">
          {{ model[field] }}
        </template>
        <template #subNum="{ model, field }">
          <!-- {{ model[field] }} -->
          <input-number
            v-model:value="model[field]"
            style="width: 260px; text-align: center"
            class="justify-center suNum"
            :min="0"
            :max="maxLength"
            @blur="deviceMapping"
            @press-enter="deviceMapping"
          >
            <template #addonBefore>
              <a-button
                :disabled="modelRef.mappingLength == 0"
                size="small"
                type="link"
                @click="handleMinusDevice"
              >
                <Icon icon="ic:baseline-minus" :size="20" />
              </a-button>
            </template>
            <template #addonAfter>
              <a-button
                :disabled="modelRef.mappingLength == maxLength"
                size="small"
                type="link"
                @click="handlePlusDevice"
              >
                <Icon icon="ic:round-plus" :size="20" />
              </a-button>
            </template>
          </input-number>
        </template>
        <template #IDInput="{ model, field }">
          <Input v-model:value="model[field]" />
          <a-button
            :disabled="modelRef.mappingLength == 0"
            size="small"
            type="link"
            @click="handleMinusDevice"
          >
            <Icon icon="ic:baseline-minus" :size="20" />
          </a-button>
        </template>
      </BasicForm>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, nextTick, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { InputNumber, Input } from 'ant-design-vue';
  // AddDevice
  import { checkDevice, AddDevice } from '/@/api/corporation/modal';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { Icon } from '/@/components/Icon/index';
  import { clamp, range } from 'lodash-es';

  export default defineComponent({
    components: { BasicModal, BasicForm, InputNumber, Icon, Input },
    props: {
      userData: { type: Object },
    },
    emits: ['register', 'update'],
    setup(props, { emit }) {
      const modelRef = ref({
        mappingLength: 0,
      });

      // const num = ref(0);
      const { t } = useI18n();
      const { createMessage } = useMessage();
      const { success, error } = createMessage;
      const maxLength = ref(20);
      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
      });

      const handlevalidator = async (item, value) => {
        let values = getFieldsValue();
        console.log('handlevalidator', value, item, values);
        let childNameList: string[] = [];
        Object.keys(values).map((ele) => {
          if (ele.includes('ID') && item.field !== ele) {
            childNameList.push(values[ele]);
          }
        });
        const issort = childNameList.some((element) => element == value);
        if (issort) {
          return Promise.reject(t('routes.devices.deviceCode'));
        }
        if (!value) {
          return Promise.resolve();
        }
        try {
          let res = await checkDevice({
            childName: value,
          });
          console.log('checkDevice', res);
          if (res.message) {
            return Promise.reject(t(`routes.devices.deviceCode50053`));
          } else {
            return Promise.resolve();
          }
        } catch (err) {
          return Promise.reject(t(`routes.devices.deviceCode50053`));
        }
      };
      const schemas: FormSchema[] = [
        {
          field: 'id',
          label: 'id',
          show: false,
          component: 'Input',
        },
        {
          field: 'subNum',
          label: 'subNum',
          show: false,
          component: 'Input',
        },
        {
          field: 'companyName',
          label: t('routes.corporation.enterpriseName'),
          slot: 'userName',
          component: 'Input',
        },
        {
          field: 'managerPhone',
          label: t('routes.corporation.enterpriseId'),
          slot: 'name',
          component: 'Input',
        },
        {
          field: 'deviceNumber',
          component: 'InputNumber',
          label: t('routes.corporation.cameraNum'),
          defaultValue: 0,
          slot: 'subNum',
          colProps: {
            span: 8,
          },
          helpMessage: t('routes.corporation.maxCountHelp'),
          // componentProps: () => {
          //   return {
          //     // xxxx props schema, tableAction, formModel  checkDevice
          //     min: 0,
          //     max: 10,
          //     // onChange: numOnChange,
          //     onblur: deviceMapping,
          //   };
          // },
        },
      ];
      // let schemasList = []
      const [
        registerForm,
        {
          setFieldsValue,
          resetFields,
          getFieldsValue,
          validate,
          appendSchemaByField,
          removeSchemaByField,
        },
      ] = useForm({
        labelWidth: 120,
        schemas,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });

      async function submitModal() {
        try {
          const values = await validate();
          console.log('values,', values);
          let childNameList: string[] = [];
          Object.keys(values).map((ele) => {
            if (ele.includes('ID')) {
              childNameList.push(values[ele]);
            }
          });

          await AddDevice({
            childNames: childNameList,
            companyId: values.id,
            subNum: String(values.subNum),
            userName: values.userName,
          });
          success(t('common.optSuccess'));
          closeModal();
          emit('update');
        } catch (error) {}
      }

      async function onDataReceive(data) {
        // 方式1;
        console.log('userName', data.record);
        let { subNum } = data.record;
        if (subNum > 979) {
          //剩余不足二十个
          maxLength.value = 999 - subNum;
        }
        resetFields();
        await setFieldsValue({
          ...data.record,
          subNum: 0,
          deviceNumber: 0,
        });
        deviceMapping();
      }

      function handleVisibleChange(v) {
        v && props.userData && nextTick(() => onDataReceive(props.userData));
      }

      async function handleCloseModal() {
        // numOnChange(0);
        await setFieldsValue({
          subNum: 0,
          deviceNumber: 0,
        });
        deviceMapping();
      }

      function setMappingDevice(devices: number, start = 0): FormSchema[] {
        return Array.from(new Array(devices)).map((_, index) => {
          const startIndex = start + index + 1;
          return {
            field: `ID${startIndex}`,
            component: 'Input',
            label: `${t('routes.corporation.deviceId')} ${startIndex}`,
            // helpMessage: [
            //   t('common.checkTips'),
            //   `${t('routes.corporation.device')} ${t('common.unusual')}`,
            // ],
            itemProps: {
              validateTrigger: 'blur',
            },
            // slot: 'IDInput',
            colProps: {
              span: 24,
            },
            rules: [
              {
                required: true,
                message: `${t('common.inputText')} ${t('routes.corporation.device')} ID`,
              },
              {
                validator: handlevalidator,
              },
            ],
          };
        });
      }

      async function deviceMapping() {
        const values = getFieldsValue();
        const devices: number = clamp(values.deviceNumber, 0, maxLength.value);
        const currentLength = unref(modelRef).mappingLength;

        const rest = devices - currentLength;
        if (rest > 0) {
          //plus
          const schemas = setMappingDevice(rest, currentLength);
          console.log('schemas', schemas);
          const patchs = schemas.map((i: FormSchema) => {
            return appendSchemaByField(i, '');
          });
          await Promise.all(patchs);
          unref(modelRef).mappingLength = devices;
          console.log('patch in');
        } else {
          // minus
          const startIndex = currentLength + rest;
          console.log('rest', rest);
          console.log('currentLength', currentLength);
          console.log('startIndex', startIndex);
          const ranges = range(startIndex + 1, currentLength + 1, 1).map((i) => {
            return `ID${i}`;
          });
          console.log('ranges', ranges);
          removeSchemaByField(ranges);
          unref(modelRef).mappingLength = devices;
        }
      }
      async function handlePlusDevice() {
        const values = getFieldsValue();
        const currentsubNum = values.deviceNumber;
        const currentDevice = clamp(currentsubNum + 1, 0, maxLength.value);
        await setFieldsValue({
          deviceNumber: currentDevice,
        });
        deviceMapping();
      }
      async function handleMinusDevice() {
        const values = getFieldsValue();
        const currentsubNum = values.deviceNumber;
        const currentDevice = clamp(currentsubNum - 1, 0, maxLength.value);
        await setFieldsValue({
          deviceNumber: currentDevice,
        });
        deviceMapping();
      }

      return {
        register,
        submitModal,
        schemas,
        registerForm,
        // numOnChange,
        modelRef,
        handleVisibleChange,
        // num,
        errorMsg: error,
        handleCloseModal,
        deviceMapping,
        t,
        handlePlusDevice,
        handleMinusDevice,
        maxLength,
      };
    },
  });
</script>
<style lang="less">
  .suNum .ant-input-number-input {
    text-align: center;
  }
</style>
