<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    title="子账号"
    @ok="saveTable"
    width="600px"
    @visible-change="handleVisibleChange"
  >
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm" :model="modelRef">
        <template #userName="{ model, field }">
          {{ model[field] }}
        </template>
        <template #name="{ model, field }">
          {{ model[field] }}
        </template>
        <template #addeduser>
          {{ myData.pagination.total || 0 }}
          <a-button @click="openTargetModal()" type="primary" preIcon="ic:outline-person-add">
            新增子账号
          </a-button>
        </template>
      </BasicForm>
      <div class="table_list">
        <BasicTable
          title="子账户列表"
          ref="tableRef"
          rowKey="id"
          :columns="columns"
          :showIndexColumn="false"
          :dataSource="myData.TableData"
          :bordered="true"
          :pagination="false"
          :beforeEditSubmit="beforeEditSubmit"
        >
          <template #action="{ record }">
            <TableAction
              :actions="[
                // {
                //   label: '编辑',
                //   icon: 'mdi:account-edit-outline',
                //   onClick: handleDelete.bind(null, record, 'edit'),
                // },
                {
                  label: '解绑',
                  icon: 'mdi:account-multiple-remove-outline',
                  onClick: handleDelete.bind(null, record, 'unbond'),
                },
              ]"
            />
          </template>
        </BasicTable>
        <AddModal @register="register4" @addtable="addTabledata" />
      </div>
    </div>
    <EditModal @register="registerEdit" />
  </BasicModal>
</template>
<script lang="ts">
  import {
    defineComponent,
    ref,
    reactive,
    nextTick,
    onMounted,
    unref,
    ComponentOptions,
    shallowRef,
    computed,
    inject,
  } from 'vue';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { BasicTable, BasicColumn, TableAction, TableActionType } 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'],
    setup(props) {
      const { t } = useI18n();
      const { createConfirm, createMessage } = useMessage();
      const currentModal = shallowRef<Nullable<ComponentOptions>>(null);
      const tableRef = ref<Nullable<TableActionType>>(null);
      const [register4, { openModal: addopenModal }] = useModal();
      const modelRef = ref({});
      const reload = inject('tablereload');
      // const editList = ref({
      //   list:[]
      // })
      const myData = reactive<tableState>({
        TableData: [],
        subNum: null,
        id: null,
        pagination: {
          total: 0,
          pageSize: 9999,
          current: 1,
        },
      });
      const getPagination = computed(() => {
        const { total, pageSize, current } = myData.pagination;
        return {
          total: total,
          pageSize,
          //size: 'small',
          current: unref(current),
          onChange(page) {
            myData.pagination.current = page;
            getApiList();
          },
        };
      });
      const columns: BasicColumn[] = [
        {
          title: t('common.fullName'),
          dataIndex: 'nickName',
          edit: true,
          editRule: true,
          width: 200,
        },
        {
          title: t('sys.login.email'),
          edit: true,
          editRule: true,
          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.rechargeId'),
          slot: 'userName',
          labelWidth: 200,
        },
        {
          field: 'companyName',
          label: t('routes.corporation.enterpriseId'),
          slot: 'name',
          component: 'Input',
          labelWidth: 200,
        },
        {
          field: 'subNum',
          component: 'InputNumber',
          label: t('routes.devices.subNum'),
          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,
          // setProps,
        },
      ] = useForm({
        labelWidth: 120,
        schemas,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });
      const [registerEdit, { openModal: EditModal }] = useModal();
      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
      });

      function onDataReceive(data) {
        console.log('Data Received', data.record);
        // 方式1;
        let { id, subNum } = data.record;
        resetFields();
        setFieldsValue({
          ...data.record,
        });
        myData.id = id;
        myData.subNum = subNum;
        getApiList();
      }
      function numOnChange(event) {
        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);
            },
          });
        }
      }
      function pageChange(page, d, a) {
        console.log('pageChange', page, d, a);
        myData.pagination.current = page;
        getApiList();
      }
      async function getApiList() {
        const { current, pageSize } = myData.pagination;
        let res = await selectUserList({
          id: myData.id,
          page: current || 1,
          limit: pageSize || 10,
        });
        myData.TableData = res.list || [];
        myData.pagination.total = res.totalCount || 0;
        console.log('selectUserList', res, myData);
      }
      async function beforeEditSubmit({ _, index, key, value }) {
        myData.TableData[index][key] = value;
        return true;
      }
      function handleVisibleChange(v) {
        v && props.userData && nextTick(() => onDataReceive(props.userData));
      }
      function openTargetModal() {
        console.log('openTargetModal');
        addopenModal(true, {
          addList: (val) => {
            console.log('addList', val, myData.subNum > myData.pagination.total);
            if (myData.subNum > myData.pagination.total) {
              myData.TableData.push(val);
              console.log('addList', val, myData.TableData);
            } else {
              createMessage.error(t('routes.devices.excess'));
            }
          },
        });
      }
      async function saveTable() {
        let tableData = tableRef.value.getDataSource() || [];
        let res = await saveSubUsers({
          id: myData.id,
          subNum: myData.subNum,
          subUsers: tableData,
        });
        console.log('saveTable', res);
        createMessage.success(t('common.o'));
        reload();
        closeModal();
      }
      function addTabledata(val) {
        console.log('addTabledata', val);
      }
      onMounted(async () => {
        myData.id && getApiList();
      });
      return {
        tableRef,
        register,
        handleDelete,
        registerEdit,
        numOnChange,
        getApiList,
        pageChange,
        myData,
        getPagination,
        schemas,
        columns,
        registerForm,
        modelRef,
        handleVisibleChange,
        beforeEditSubmit,
        register4,
        openTargetModal,
        currentModal,
        addopenModal,
        saveTable,
        closeModal,
        addTabledata,
        reload,
        t,
      };
    },
  });
</script>
