<template>
  <PageWrapper contentBackground>
    <div class="desc-wrap-BasicTable">
      <BasicTable @register="registerTable">
        <template #toolbar>
          <a-button type="primary" v-if="hasPermission([RoleEnum.SUPER])" @click="handleAdd"> {{t('routes.retailer.allff')}}</a-button>
        </template>
        <template #action="{ record }">
          <TableAction
            stopButtonPropagation
            :actions="[
              {
                label: t('routes.retailer.ff'),
                ifShow: !record.subAgentName,
                //icon: 'la:file-invoice-dollar',
                onClick: headleDetails.bind(null, record),
              },
              {
                label: t('routes.retailer.Unbind'),
                ifShow: !!record.subAgentName,
                //icon: 'la:file-invoice-dollar',
                onClick: headleUnbind.bind(null, record),
              },
            ]"
          />
        </template>
      </BasicTable>
    </div>
    <distributeModal @reload="reload" @register="registerAddModal" />
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, h, onMounted, computed } from 'vue';
  import {
    BasicTable,
    useTable,
    TableAction,
    BasicColumn,
    TableImg,
    FormProps,
  } from '/@/components/Table';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { RoleEnum } from '/@/enums/roleEnum';
  import { PageWrapper } from '/@/components/Page';
  import { Descriptions } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { cameraList } from '/@/api/customer';
  import { cameraDelete } from '/@/api/device';
  import { useModal } from '/@/components/Modal';
  import { getSubAgent } from '/@/api/retailer';
  import { useRouter } from 'vue-router';
  import { UnbindCameraApi } from '/@/api/account';
  import { usePermissionStore } from '/@/store/modules/permission';
  import { useLocaleStore } from '/@/store/modules/locale';
  import { dincrementList } from '/@/api/equity';
  import { useUserStore } from '/@/store/modules/user';
  import distributeModal from './distributeModal.vue';
  export default defineComponent({
    components: {
      BasicTable,
      TableAction,
      PageWrapper,
      TableImg,
      distributeModal,
      [Descriptions.name]: Descriptions,
      [Descriptions.Item.name]: Descriptions.Item,
    },
    setup() {
      const { t } = useI18n();
      const userStore = useUserStore();
      const getUserInfo = userStore.getUserInfo;
      const { hasPermission } = usePermission();
      const { createMessage, createConfirm } = useMessage();
      const permissionStore = usePermissionStore();
      const { getCheckPerm } = permissionStore;
      const router = useRouter();
      const localeStore = useLocaleStore();
      const isEn = computed(() => localeStore.getLocale === 'en');
      const companyId: Number = router.currentRoute.value.params.id - 0;
      const [registerAddModal, { openModal }] = useModal();
      onMounted(() => {
        // console.log(router.currentRoute.value.params.id);
      });
      const columns: BasicColumn[] = [
        {
          title: t('routes.device.snCode'),
          dataIndex: 'snCode',
          width: 180,
        },
        {
          title: t('routes.device.wifiName'),
          dataIndex: 'wifiName',
          width: 150,
        },
        {
          title: t('routes.device.deviceType'),
          dataIndex: 'type',
          ellipsis: false,
          width: 100,
          customRender: ({ record }) => {
            let typeObj = {
              '0': t('routes.device.type.0'),
              '1': t('routes.device.type.1'),
              '2': t('routes.device.type.2'),
              '9': t('routes.device.type.9'),
              '10': t('routes.device.type.10'),
              '11': t('routes.device.type.11'),
            };
            return typeObj[record.type];
          },
        },

        {
          title: t('routes.device.activatedTime'),
          dataIndex: 'activatedTime',
          width: 180,
        },
        {
          title: t('routes.retailer.fxs'),
          dataIndex: 'subAgentName',
          ellipsis: true,
          width: 160,
          ifShow: hasPermission([RoleEnum.SUPER]),
          customRender({ record }) {
            return record.subAgentName || '-';
          }
        },
        {
          title: t('routes.equity.Type'),
          dataIndex: 'validTimeType',
          width: 180,
          customRender({ record }) {
            return record.validTimeType == 0
              ? t('routes.equity.equityType.0')
              : record.validTimeType == 1
              ? t('routes.equity.equityType.3')
              : t('routes.device.NoBind');
          },
        },
        {
          title: t('routes.device.statusName'),
          dataIndex: 'incrementStatus',
          customRender({ record }) {
            if (record.incrementStatus == -1) {
              return '-';
            } else {
              return record.incrementStatus == 0
                ? t('routes.device.status.0')
                : t('routes.device.status.1');
            }
          },
          width: 180,
        },
        {
          title: t('routes.device.userName'),
          dataIndex: 'userName',
          width: 180,
          customRender({ record }) {
            return record.userName ? record.userName : '-';
          },
        },
      ];
      const searchForm: Partial<FormProps> = {
        labelWidth: 120,
        autoAdvancedLine: 1,
        actionColOptions: {
          span: 24,
        },
        schemas: [
          {
            field: 'snCode',
            component: 'Input',
            label: t('routes.device.snCode'),
            colProps: {
              xl: 8,
              xxl: 8,
            },
          },
          {
            field: 'type',
            component: 'Select',
            label: t('routes.device.deviceType'),
            colProps: {
              xl: 8,
              xxl: 8,
            },
            componentProps: {
              options: [
                {
                  //   label: t('routes.device.type.0'),
                  //   value: 0,
                  //   key: '0',
                  // },{
                  label: t('routes.device.type.1'),
                  value: 1,
                  key: '1',
                },
                {
                  label: t('routes.device.type.2'),
                  value: 9,
                  key: '9',
                },
                {
                  label: t('routes.device.type.3'),
                  value: 10,
                  key: '10',
                },
                {
                  label: t('routes.device.type.11'),
                  value: 11,
                  key: '11',
                },
              ],
            },
          },
          {
            field: 'userName',
            component: 'Input',
            label: t('routes.device.userName'),
            colProps: {
              xl: 8,
              xxl: 8,
            },
          },
          {
            field: 'incrementTypeId',
            component: 'ApiSelect',
            label: t('routes.equity.Type'),
            componentProps: {
              maxLength: 50,
              api: async function () {
                const list = await dincrementList();
                return list.map((ele) => {
                  return {
                    name: t(`routes.finance.equityType.${ele.validTimeType}`),
                    value: ele.id,
                  };
                });
              },
              numberToString: true,
              labelField: 'name',
              valueField: 'value',
              immediate: true,
            },
            colProps: {
              xl: 8,
              xxl: 8,
            },
          },
          {
            field: 'incrementStatus',
            component: 'Select',
            label: t('routes.device.statusName'),
            colProps: {
              xl: 8,
              xxl: 8,
            },
            componentProps: {
              options: [
                {
                  label: t('routes.device.status.0'),
                  value: '0',
                  key: '0',
                },
                {
                  label: t('routes.device.status.1'),
                  value: '1',
                  key: '1',
                },
              ],
            },
          },
          {
            field: 'bindStatus',
            component: 'Select',
            label: t('routes.device.bindStatus'),
            colProps: {
              xl: 8,
              xxl: 8,
            },
            componentProps: {
              options: [
                {
                  label: t('routes.device.status.2'),
                  value: '1',
                  key: '1',
                },
                {
                  label: t('routes.device.status.3'),
                  value: '0',
                  key: '0',
                },
              ],
            },
          },
          {
            field: 'subAgentId',
            component: 'ApiSelect',
            ifShow: hasPermission([RoleEnum.SUPER]),
            label: t('routes.device.subAgentName'),
            componentProps: {
              maxLength: 50,
              api: getSubAgent,
              numberToString: true,
              labelField: 'name',
              valueField: 'id',
              immediate: true,
              style: { maxWidth: '430px' },
            },
            colProps: {
              xl: 8,
              xxl: 8,
            },
          },
        ],
      };
      const [registerTable, { reload }] = useTable({
        api: cameraList,
        columns: columns,
        searchInfo: { companyId },
        useSearchForm: true,
        formConfig: searchForm,
        showTableSetting: true,
        showIndexColumn: false,
        rowKey: 'id',
        beforeFetch: (T) => {
          if (T.ctivated) {
            T.activatedStartTime = T.ctivated[0];
            T.activatedEndTime = T.ctivated[1];
          }
          return T;
        },
        fetchSetting: {
          pageField: 'pageNum',
          sizeField: 'pageSize',
          listField: 'list',
          totalField: 'total',
        },
        actionColumn: {
          width: 150,
          title: t('common.operating'),
          ifShow: hasPermission([RoleEnum.SUPER]),
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
        canResize: false,
      });
      async function headleUnbind(record: Recordable) {
        createConfirm({
          iconType: 'warning',
          title: () => h('span', t('common.reminder')),
          content: t('routes.retailer.UnbindTips'),
          onOk: async () => {
            await UnbindCameraApi({ id: record.id });
            createMessage.success(t('common.optSuccess'));
            reload();
          },
        });
      }
      async function handleDelete(record: Recordable) {
        createConfirm({
          iconType: 'warning',
          title: () => h('span', t('common.reminder')),
          content: '删除设备后需要重新入库<br/>确定删除吗?',
          onOk: async () => {
            await cameraDelete({ id: record.id });
            createMessage.success(t('common.optSuccess'));
            reload();
          },
        });
      }
      function handleAdd() {
        openModal(true, {});
      }
      function headleDetails(record: Recordable) {
        openModal(true, record);
      }
      return {
        registerTable,
        headleUnbind,
        reload,
        handleDelete,
        getCheckPerm,
        handleAdd,
        headleDetails,
        registerAddModal,
        hasPermission,
        RoleEnum,
        t,
      };
    },
  });
</script>
<style lang="less" scoped>
  .desc-wrap-BasicTable {
    background-color: #f0f2f5;
    .vben-basic-table-form-container {
      padding: 0;
    }
  }
</style>
