<template>
  <PageWrapper contentBackground>
    <div class="desc-wrap-BasicTable">
      <BasicTable @register="registerTable">
        <template #toolbar>
          <a-button
            v-if="
              hasPermission([
                RoleEnum.SUPER,
                RoleEnum.TEST,
                RoleEnum.LEVEL2,
                RoleEnum.LEVEL2s,
                RoleEnum.DISTRIBUTOR,
              ])
            "
            @click="getTemplate"
          >
            {{ t('routes.device.export') }}</a-button
          >
          <a-button
            type="primary"
            v-if="hasPermission([RoleEnum.SUPER, RoleEnum.TEST, RoleEnum.LEVEL2, RoleEnum.LEVEL2s])"
            @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" />
    <subAgentInfoModal @register="registerSubAgentInfoModal" />
  </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 { downCameraExport } from '/@/api/customer';
  import { Icon } from '/@/components/Icon';
  import distributeModal from './distributeModal.vue';
  import subAgentInfoModal from './subAgentInfoModal.vue';
  export default defineComponent({
    components: {
      BasicTable,
      TableAction,
      PageWrapper,
      TableImg,
      Icon,
      distributeModal,
      subAgentInfoModal,
      [Descriptions.name]: Descriptions,
      [Descriptions.Item.name]: Descriptions.Item,
    },
    setup() {
      const { t, locale } = 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();
      const [registerSubAgentInfoModal, { openModal: openSubAgentInfoModal }] = useModal();
      const subAgentInfoText = computed(() =>
        isEn.value ? 'Distribution Log' : '\u5206\u914d\u65e5\u5fd7',
      );
      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: 'outTime',
          width: 180,
        },
        {
          title: t('routes.retailer.fxs'),
          dataIndex: 'subAgentName',
          ellipsis: false,
          width: 240,
          // ifShow: hasPermission([RoleEnum.SUPER]),
          customRender({ record }) {
            if (!record.subAgentName) {
              return '-';
            }
            return h('div', { class: 'sub-agent-cell' }, [
              h('span', { class: 'sub-agent-name' }, record.subAgentName),
              h(
                'a',
                {
                  class: 'sub-agent-info-link',
                  title: subAgentInfoText.value,
                  onClick: (event) => {
                    event.stopPropagation();
                    handleViewSubAgentInfo(record);
                  },
                },
                [h(Icon, { icon: 'ion:information-circle-outline', size: 16 })],
              ),
            ]);
          },
        },
        {
          title: t('routes.retailer.activatedTime'),
          dataIndex: 'activatedTime',
          width: 220,
        },
        {
          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.incrementEndTime'),
          dataIndex: 'incrementEndTime',
          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,
            },
          },

          {
            field: 'timeList',
            label: t('routes.device.activatedTime'),
            component: 'RangePicker',
            componentProps: {
              maxLength: 100,
              valueFormat: 'YYYY-MM-DD',
              format: 'YYYY-MM-DD',
            },
            colProps: {
              xl: 7,
              xxl: 7,
            },
          },
        ],
      };
      const [registerTable, { reload }] = useTable({
        api: cameraList,
        columns: columns,
        searchInfo: { companyId },
        useSearchForm: true,
        formConfig: searchForm,
        showTableSetting: true,
        showIndexColumn: false,
        rowKey: 'id',
        // beforeFetch: (T) => {
        //   if (T.timeList) {
        //     T.activatedStartTime = T.timeList[0];
        //     T.activatedEndTime = T.timeList[1];
        //   }
        //   return T;
        // },
        fetchSetting: {
          pageField: 'pageNum',
          sizeField: 'pageSize',
          listField: 'list',
          totalField: 'total',
        },
        actionColumn: {
          width: 150,
          title: t('common.operating'),
          ifShow: hasPermission([RoleEnum.SUPER, RoleEnum.TEST, RoleEnum.LEVEL2, RoleEnum.LEVEL2s]),
          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();
          },
        });
      }
      async function getTemplate() {
        const lang = locale.value == 'zh_CN' ? 'zh' : 'en';
        try {
          const res = await downCameraExport({ lang });
        } catch (error) {
          console.log('not passing', error);
        }
      }
      function handleAdd() {
        // 打开模态框
        openModal(true, {});
      }
      function headleDetails(record: Recordable) {
        openModal(true, record);
      }
      function handleViewSubAgentInfo(record: Recordable) {
        openSubAgentInfoModal(true, record);
      }
      return {
        getTemplate,
        registerTable,
        headleUnbind,
        reload,
        handleDelete,
        getCheckPerm,
        handleAdd,
        headleDetails,
        registerAddModal,
        registerSubAgentInfoModal,
        hasPermission,
        RoleEnum,
        t,
      };
    },
  });
</script>
<style lang="less" scoped>
  .desc-wrap-BasicTable {
    background-color: #f0f2f5;
    .vben-basic-table-form-container {
      padding: 0;
    }
  }

  :deep(.sub-agent-cell) {
    display: inline-flex;
    max-width: 100%;
    align-items: center;
    gap: 10px;
  }

  :deep(.sub-agent-name) {
    overflow: hidden;
    min-width: 0;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  :deep(.sub-agent-info-link) {
    flex: none;
    white-space: nowrap;
    display: inline-flex;
    align-items: center;
    justify-content: center;
  }
</style>
