<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="t('routes.devices.addCamera')"
    @visible-change="handleVisibleChange"
    @ok="handleSubmit"
    @cancel="handleClose"
  >
    <div class="pt-2px pr-3px">
      <BasicForm @register="registerForm" :model="model" />
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, nextTick, onMounted } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  // allCompanyApi
  import { addCameraApi } from '/@/api/device/list';
  import { useI18n } from '/@/hooks/web/useI18n';
  //   address: "11111"
  // balance: "111"
  // cameraType: "4"
  // childName: "11111"
  // companyId: 1146
  // orderSn: "1111"
  // own: "0"
  // rnd: 0.9923218970879999
  // snCode: "1111"
  // wifiName: "1111"
  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      userData: { type: Object },
    },
    emits: ['update', 'register'],
    setup(props, { emit }) {
      const modelRef = ref({});
      const { createMessage } = useMessage();
      const schemas: FormSchema[] = [
        {
          field: 'own',
          component: 'Select',
          label: t('routes.devices.own'),
          colProps: {
            span: 24,
          },
          rules: [
            {
              required: true,
              validator: async (rule, value) => {
                if (!value && value != 0) {
                  return Promise.reject(t('routes.devices.own.required'));
                }
                return Promise.resolve();
              },
              trigger: 'change',
            },
          ],
          componentProps: {
            placeholder: t('routes.devices.own.placeholder'),
            options: [0, 2, 1].map((ele) => {
              return { value: ele, key: ele, label: renderOwnTypeLabel(ele) };
            }),
          },
          required: true,
        },
        {
          field: 'cameraType',
          component: 'Select',
          label: t('routes.devices.cameraType'),
          rules: [
            {
              required: true,
              validator: async (rule, value) => {
                if (!value) {
                  return Promise.reject(t('routes.devices.cameraType.required'));
                }
                return Promise.resolve();
              },
              trigger: 'change',
            },
          ],
          colProps: {
            span: 24,
          },
          componentProps: {
            placeholder: t('routes.devices.cameraType.placeholder'),
            options: [4, 9, 10, 11, 6].map((ele) => {
              return { value: ele, key: ele, label: rendercameraTypeLabel(ele) };
            }),
          },
        },

        {
          field: 'childName',
          component: 'Input',
          label: t('routes.devices.childName'),
          rules: [
            {
              required: true,
              message: t('routes.devices.childName.required'),
            },
          ],
          colProps: {
            span: 24,
          },
          componentProps: {
            placeholder: t('routes.devices.childName.placeholder'),
          },
        },
        {
          field: 'wifiName',
          component: 'Input',
          label: t('routes.devices.wifiName'),
          rules: [
            {
              required: true,
              message: t('routes.devices.wifiName.required'),
              trigger: 'change',
            },
          ],
          colProps: {
            span: 24,
          },
          componentProps: {
            placeholder: t('routes.devices.wifiName.placeholder'),
          },
        },
        {
          field: 'address',
          component: 'Input',
          // required: true,
          label: t('routes.devices.address'),
          rules: [
            {
              required: true,
              trigger: ['change', 'blur'],
              message: t('routes.devices.address.required'),
            },
          ],
          colProps: {
            span: 24,
          },
          componentProps: {
            placeholder: t('routes.devices.address.placeholder'),
          },
        },
        {
          field: 'snCode',
          component: 'Input',
          label: t('routes.devices.snCode'),
          rules: [
            {
              required: true,
              message: t('routes.devices.snCode.required'),
            },
          ],
          componentProps: {
            placeholder: t('routes.devices.snCode.placeholder'),
          },
          // ifShow: ({ model }) => {
          //   console.log('record', model.cameraType);

          //   return model.cameraType && model.cameraType !== 6;
          // },
          colProps: {
            span: 24,
          },
        },
        // {
        //   field: 'balance',
        //   component: 'Input',
        //   label: t('routes.devices.balance'),
        //   colProps: {
        //     span: 24,
        //   },
        // },
        // {
        //   field: 'orderSn',
        //   component: 'Input',
        //   label: t('routes.devices.orderSn'),
        //   colProps: {
        //     span: 24,
        //   },
        //   required: true,
        // },
        // {
        //   field: 'companyId',
        //   component: 'ApiSelect',
        //   label: t('routes.devices.companyId'),
        //   componentProps: {
        //     api: allCompanyApi,
        //     numberToString: true,
        //     labelField: 'companyName',
        //     valueField: 'id',
        //     immediate: true,
        //     params: {
        //       page: 1,
        //       limit: 1000,
        //     },
        //   },
        //   colProps: {
        //     span: 24,
        //   },
        // },
      ];
      const [
        registerForm,
        {
          getFieldsValue,
          validateFields,
          // appendSchemaByField,
          // removeSchemaByField,
          resetFields,
          // setProps
        },
      ] = useForm({
        labelWidth: 120,
        schemas,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });
      onMounted(() => {});
      let addListFunc = () => {};
      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
      });
      function renderOwnTypeLabel(type: number): string {
        switch (type) {
          case 0:
            return t('routes.devices.ownName.0');
          case 2:
            return t('routes.devices.ownName.2');
          case 1:
            return t('routes.devices.ownName.1');
          case 3:
            return t('routes.devices.ownName.1');
          default:
            return '';
        }
      }
      function rendercameraTypeLabel(cameraType: number): string {
        switch (cameraType) {
          case 4:
            return t('routes.devices.cameraName.4');
          case 1:
            return t('routes.devices.cameraName.4');
          case 9:
            return t('routes.devices.cameraName.9');
          case 10:
            return t('routes.devices.cameraName.10');
          case 11:
            return t('routes.devices.cameraName.11');
          case 6:
            return t('routes.devices.cameraName.6');
          default:
            return '';
        }
      }
      function onDataReceive(data) {
        console.log('Data Received', data);
        const { addList } = data;
        if (typeof addList === 'function') {
          //是函数    其中 FunName 为函数名称
          addListFunc = addList;
        }
      }
      const handleSubmit = async () => {
        console.log('getFieldsValue()', getFieldsValue());
        try {
          const data = await validateFields();
          const param = await getFieldsValue();
          let res = await addCameraApi(param);
          console.log('getFieldsValue()', res, data, param);
          if (res.code) {
            createMessage.error(res.error || t('common.optFail'));
          } else {
            emit('update');
            closeModal();
            resetFields();
          }
        } catch (error) {
          console.log('not passing', error);
        }
      };
      function handleVisibleChange(v) {
        v && props.userData && nextTick(() => onDataReceive(props.userData));
      }
      function handleClose() {
        resetFields();
      }

      return {
        register,
        rendercameraTypeLabel,
        renderOwnTypeLabel,
        schemas,
        registerForm,
        model: modelRef,
        handleVisibleChange,
        handleSubmit,
        handleClose,
        addListFunc,
        t,
      };
    },
  });
</script>
