<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="t('routes.devices.title')"
    @ok="saveTable"
    width="600px"
    @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>
        <!-- :disabled="model.subNum == 0" -->
        <template #addeduser="{ model, field }">
          {{ model[field] || 0 }}
          <a-button @click="openTargetModal()" type="primary" preIcon="ic:outline-person-add">
            {{ t('routes.devices.add') }}{{ t('routes.devices.title') }}
          </a-button>
        </template>
      </BasicForm>
      <div class="table_list">
        <BasicTable
          @register="registerSubtable"
          :beforeEditSubmit="beforeEditSubmit"
          :searchInfo="searchInfo"
        >
          <template #action="{ record }">
            <TableAction
              :actions="[
                // {
                //   label: '编辑',
                //   icon: 'mdi:account-edit-outline',
                //   onClick: handleDelete.bind(null, record, 'edit'),
                // },
                {
                  label: t('common.unbind'),
                  icon: 'mdi:account-multiple-remove-outline',
                  onClick: handleDelete.bind(null, record, 'unbond'),
                },
              ]"
            />
          </template>
        </BasicTable>
        <AddModal @tablelist="getTableList" @register="registerModal" @submit="handleAddUser" />
      </div>
    </div>
    <EditModal @register="registerEdit" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, reactive, nextTick, unref } from 'vue';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { BasicTable, useTable, BasicColumn, TableAction } from '/@/components/Table';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { selectUserList, saveSubUsers } from '/@/api/corporation/modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import EditModal from './EditModal.vue';
  // import { tableState } from './types/hooks';
  import AddModal from './AddModal.vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  export default defineComponent({
    components: { BasicModal, BasicForm, BasicTable, AddModal, TableAction, EditModal },
    props: {
      userData: { type: Object },
    },
    emits: ['addtable', 'register', 'update'],
    setup(props, { emit }) {
      const { t } = useI18n();
      const { createConfirm, createMessage } = useMessage();

      const [registerModal, { openModal: addopenModal }] = useModal();

      const modelRef = reactive({
        id: 0,
        subNum: 0,
      });
      const searchInfo = reactive({
        limit: 9999,
        id: 0,
        page: 1,
      });
      const columns: BasicColumn[] = [
        {
          title: t('common.fullName'),
          dataIndex: 'nickName',
          edit: true,
          editRule: async (text) => {
            console.log('editRule', text);
            if (text && text.length > 25) {
              return t('routes.devices.maxlength');
            }
            return '';
          },
          width: 200,
        },
        {
          title: t('sys.login.email'),
          width: 200,
          dataIndex: 'userName',
        },
        {
          title: t('common.operating'),
          dataIndex: '',
          slots: { customRender: 'action' },
          width: 100,
        },
      ];
      const schemas: FormSchema[] = [
        {
          field: 'managerPhone',
          component: 'Input',
          label: `${t('routes.corporation.enterpriseId')} ：`,
          slot: 'userName',
          labelWidth: 200,
        },
        {
          field: 'companyName',
          label: `${t('routes.corporation.enterpriseName')} ：`,
          slot: 'name',
          component: 'Input',
          labelWidth: 200,
        },
        {
          field: 'totalSubNum',
          component: 'InputNumber',
          label: `${t('routes.devices.subNum')} ：`,
          show: false,
          labelWidth: 200,
          componentProps: () => {
            return {
              // xxxx props schema, tableAction, formModel  checkDevice
              min: 0,
              onChange: numOnChange,
            };
          },
        },
        {
          field: 'addeduser',
          label: `${t('routes.devices.addeduser')}`,
          labelWidth: 200,
          slot: 'addeduser',
          component: 'Input',
        },
      ];
      const [
        registerForm,
        {
          setFieldsValue,
          resetFields,
          getFieldsValue,
          // setProps,
        },
      ] = useForm({
        labelWidth: 120,
        schemas,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });

      const [
        registerSubtable,
        {
          reload: reloadSubtable,
          updateTableDataRecord,
          deleteTableDataRecord,
          getDataSource,
          insertTableDataRecord,
        },
      ] = useTable({
        title: `${t('routes.devices.listTile')}`,
        rowKey: 'userName',
        api: selectUserList,
        immediate: false,
        columns: columns,
        showIndexColumn: false,
        bordered: true,
        pagination: false,
      });

      const [registerEdit, { openModal: EditModal }] = useModal();
      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
      });

      async function onDataReceive(data) {
        console.log('Data Received', data.record);
        // 方式1;
        const { id, subNum } = data.record;
        resetFields();
        setFieldsValue({
          ...data.record,
        });
        modelRef.id = id;
        modelRef.subNum = subNum;

        searchInfo.id = id;
        await reloadSubtable();

        const total = getDataSource();
        console.log('total', total);
        setFieldsValue({
          addeduser: total?.length || 0,
        });
      }
      function numOnChange(data) {
        console.log('data', data);
        modelRef.subNum = data;
        // myData.subNum = event;
        // console.log('numOnChange', event);
      }
      async function handleDelete(item, type) {
        console.log('handleDelete', item, type);
        if (type == 'edit') {
          //编辑
          const { memoName, phone } = item;
          EditModal(true, {
            memoName,
            phone,
          });
        } else {
          //解除
          createConfirm({
            iconType: 'warning',
            title: '提示',
            content: t('routes.devices.unbindWarning'),
            onOk: async () => {
              // tableRef.value.deleteTableDataRecord(item.id);
              deleteTableDataRecord(item.userName);
            },
          });
        }
      }

      async function beforeEditSubmit({ record, _, key, value }) {
        updateTableDataRecord(record.userName, { ...record, [key]: value });
      }
      function handleVisibleChange(v) {
        v && props.userData && nextTick(() => onDataReceive(props.userData));
      }
      function openTargetModal() {
        console.log('openTargetModal');
        addopenModal(true);
      }
      async function saveTable() {
        // let tableData = tableRef.value.getDataSource() || [];
        let tableData = getDataSource();
        let res = await saveSubUsers({
          id: modelRef.id,
          subNum: modelRef.subNum,
          subUsers: tableData,
        });
        console.log('saveTable', res);
        createMessage.success(t('common.optSuccess'));
        // reload();
        emit('update');
        closeModal();
      }
      function addTabledata(val) {
        console.log('addTabledata', val);
      }
      function getTableList(callback) {
        let data = getFieldsValue();
        let tableList = unref(getDataSource());
        setFieldsValue({
          subNum: Number(data.subNum) - 1,
        });
        callback(tableList);
      }
      function handleAddUser(newUser) {
        console.log('newUser', newUser);
        insertTableDataRecord({
          userName: newUser.managerPhone,
          nickName: newUser.companyName,
        });
      }
      return {
        register,
        handleDelete,
        registerEdit,
        numOnChange,
        modelRef,
        schemas,
        columns,
        registerForm,

        handleVisibleChange,
        beforeEditSubmit,
        registerModal,
        openTargetModal,

        addopenModal,
        saveTable,
        closeModal,
        addTabledata,
        t,
        registerSubtable,
        reloadSubtable,
        searchInfo,
        handleAddUser,
        getTableList,
      };
    },
  });
</script>
