<template>
  <PageContainer v-if="!visible" :pageHeaderRender="false" style="padding: 0 10px 10px 10px">
    <ProSearch :columns="searchFormSchema" target="product-manage" @search="handleSearch" />
    <FullPage style="min-height: calc(100vh - 186px)">
      <JTable
        model="CARD"
        :columns="columns"
        :request="queryProductList"
        ref="tableRef"
        :defaultParams="{
          column: 'createTime',
          order: 'desc',
          pageSize: 9
        }"
        :params="params"
      >
        <template #headerTitle>
          <Space>
            <PermissionButton type="primary" @click="add">
              <template #icon><AIcon type="PlusOutlined" /></template>
              新增
            </PermissionButton>
            <!--  <j-upload name="file" accept=".json" :showUploadList="false" :before-upload="beforeUpload">
              <PermissionButton type="primary"><j-aIcon type="ImportOutlined" />导入</PermissionButton>
            </j-upload>-->
          </Space>
        </template>
        <template #deviceType="slotProps">
          <div>{{ slotProps.deviceType.text }}</div>
        </template>
        <template #card="slotProps">
          <CardBox
            :value="slotProps"
            :actions="getActions(slotProps, 'card')"
            v-bind="slotProps"
            :active="_selectedRowKeys.includes(slotProps.id)"
            :status="slotProps.state"
            @click="handleView(slotProps.id)"
            :statusText="slotProps.state === 1 ? '正常' : '禁用'"
            :statusNames="{
              1: 'processing',
              0: 'error'
            }"
          >
            <template #img>
              <slot name="img">
                <img
                  :src="getImage(slotProps.photoUrl, false) || getImage('/device-product.png')"
                  class="productImg"
                  alt="product"
                />
              </slot>
            </template>
            <template #content>
              <Ellipsis style="width: calc(100% - 100px); margin-bottom: 18px"
                ><span style="font-weight: 600; font-size: 16px">
                  {{ slotProps.name }}
                </span></Ellipsis
              >
              <Row>
                <Col :span="12">
                  <div class="card-item-content-text"> 设备类型 </div>
                  <div>{{ slotProps?.deviceType?.text }}</div>
                </Col>
                <Col :span="12">
                  <div class="card-item-content-text"> 接入方式 </div>
                  <Ellipsis
                    ><div>
                      {{ slotProps?.accessName ? slotProps?.accessName : '未接入' }}
                    </div></Ellipsis
                  >
                </Col>
              </Row>
            </template>
            <template #actions="item">
              <PermissionButton
                :disabled="item.disabled"
                :popConfirm="item.popConfirm"
                :tooltip="{
                  ...item.tooltip
                }"
                @click="item.onClick"
              >
                <AIcon type="DeleteOutlined" v-if="item.key === 'delete'" />
                <template v-else>
                  <AIcon :type="item.icon" />
                  <span>{{ item?.text }}</span>
                </template>
              </PermissionButton>
            </template>
          </CardBox>
        </template>
        <template #state="slotProps">
          <BadgeStatus
            :text="slotProps.state === 1 ? '正常' : '禁用'"
            :status="slotProps.state"
            :statusNames="{
              1: 'processing',
              0: 'error'
            }"
          />
        </template>
        <template #action="slotProps">
          <Space :size="16">
            <template v-for="i in getActions(slotProps, 'table')" :key="i.key">
              <PermissionButton
                :disabled="i.disabled"
                :popConfirm="i.popConfirm"
                :tooltip="{
                  ...i.tooltip
                }"
                @click="i.onClick"
                type="link"
                style="padding: 0"
                :danger="i.key === 'delete'"
              >
                <template #icon><AIcon :type="i.icon" /></template>
              </PermissionButton>
            </template>
          </Space>
        </template>
      </JTable>
    </FullPage>
  </PageContainer>
  <!-- 新增、编辑 -->
  <Save v-if="saveShow" ref="saveRef" :isAdd="isAdd" :title="title" @success="refresh" @show-detail="handleView" />
  <Detail v-if="visible" :id="productId" />
</template>

<script setup lang="ts">
  import {
    queryProductList,
    getProviders,
    queryGatewayList,
    _deploy,
    _undeploy,
    deleteProduct
  } from '../../../api/device/product';
  import { downloadObject, accessConfigTypeFilter, getImage, onlyMessage } from '@jdlinker/utils';
  import { omit } from 'lodash-es';
  import Save from './Save/index.vue';
  import Detail from './Detail/index.vue';
  import { nextTick, provide, ref, onMounted, watch } from 'vue';
  import { useRoute } from 'vue-router';
  import JTable from '../../../components/UI/Table/index';
  import { FormSchema, JSearch as ProSearch, FullPage, PermissionButton, CardBox, BadgeStatus } from '@jdlinker/ui';
  // @ts-ignore
  import { PageContainer, AIcon, Space, Ellipsis, Row, Col } from 'linker-ui-components';
  /**
   * 表格数据
   */
  const productId = ref<any>('');
  const visible = ref<boolean>(false);
  const isAdd = ref<number>(0);
  const title = ref<string>('');
  const params = ref<Record<string, any>>({});
  const accessProviderOptions = ref<any>([]);
  const typeList = ref<any>([]);
  const route = useRoute();
  const saveShow = ref<boolean>(false);

  watch(
    () => route.query.id,
    (newId) => {
      if (newId && route.name === 'iot-device-Product') {
        visible.value = true;
        productId.value = route.query.id;
      }
    },
    { immediate: true, deep: true }
  );

  const getAccessProviderOptions = () => {
    return getProviders().then((resp: any) => {
      const data = resp.result || [];
      accessProviderOptions.value = accessConfigTypeFilter(data);
    });
  };

  const getAccessOptions = () => {
    return queryGatewayList({
      paging: false
    }).then((resp: any) => {
      typeList.value = [];
      typeList.value = resp.result.map((item: any) => ({
        label: item.name,
        value: item.id
      }));
    });
  };

  onMounted(() => {
    getAccessProviderOptions();
    getAccessOptions();
  });

  const searchFormSchema: FormSchema[] = [
    {
      label: '产品名称',
      field: 'name',
      component: 'Input'
    },
    {
      label: '网关类型',
      field: 'accessProvider',
      component: 'Select',
      componentProps: {
        options: accessProviderOptions
      }
    },
    {
      label: '状态',
      field: 'state',
      component: 'Select',
      componentProps: {
        options: [
          {
            label: '正常',
            value: 1
          },
          {
            label: '禁用',
            value: 0
          }
        ]
      }
    }
  ];
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      scopedSlots: true,
      align: 'center',
      width: 200,
      ellipsis: true
    },
    {
      title: '产品名称',
      dataIndex: 'name',
      key: 'name',
      width: 220,
      ellipsis: true,
      align: 'center'
    },
    {
      title: '接入方式',
      dataIndex: 'accessName',
      key: 'accessName',
      width: 220,
      ellipsis: true,
      align: 'center'
    },
    {
      title: '设备类型',
      dataIndex: 'deviceType',
      key: 'deviceType',
      scopedSlots: true,
      ellipsis: true,
      align: 'center',
      width: 120
    },
    {
      title: '状态',
      dataIndex: 'state',
      key: 'state',
      scopedSlots: true,
      ellipsis: true,
      align: 'center',
      width: 90
    },
    {
      title: '说明',
      dataIndex: 'describe',
      key: 'describe',
      ellipsis: true
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      fixed: true,
      width: 200,
      scopedSlots: true,
      ellipsis: true
    }
  ];
  const _selectedRowKeys = ref<string[]>([]);
  const getActions = (data: Partial<Record<string, any>>, type: 'card' | 'table'): any[] => {
    if (!data) {
      return [];
    }
    const actions = [
      {
        key: 'view',
        text: '查看',
        tooltip: {
          title: '查看'
        },
        icon: 'EyeOutlined',
        onClick: () => {
          handleView(data.id);
        }
      },
      {
        key: 'update',
        text: '编辑',
        tooltip: {
          title: '编辑'
        },
        icon: 'EditOutlined',
        onClick: () => {
          title.value = '编辑';
          isAdd.value = 2;
          saveShow.value = true;
          nextTick(() => {
            saveRef.value.show(data);
          });
        }
      },
      {
        key: 'export',
        text: '导出',
        tooltip: {
          title: '导出'
        },

        icon: 'icon-xiazai',
        onClick: () => {
          const extra = omit(data, [
            'transportProtocol',
            'protocolName',
            'accessId',
            'accessName',
            'accessProvider',
            'messageProtocol'
          ]);
          downloadObject(extra, '产品');
        }
      },
      {
        key: 'action',
        text: data.state !== 0 ? '禁用' : '启用',
        tooltip: {
          title: data.state !== 0 ? '禁用' : '启用'
        },
        icon: data.state !== 0 ? 'StopOutlined' : 'CheckCircleOutlined',
        popConfirm: {
          title: `确认${data.state !== 0 ? '禁用' : '启用'}?`,
          onConfirm: async () => {
            let response;
            if (data.state !== 0) {
              response = await _undeploy(data.id);
            } else {
              response = await _deploy(data.id);
            }
            if (response.code === 200) {
              onlyMessage('操作成功！', 'success');
              tableRef.value?.reload();
            } else {
              onlyMessage(response.message, 'error');
            }
          }
        }
      },
      {
        key: 'delete',
        text: '删除',
        disabled: data.state !== 0,
        tooltip: {
          title: data.state !== 0 ? '已启用的产品不能删除' : '删除'
        },
        popConfirm: {
          title: '确认删除?',
          onConfirm: async () => {
            const resp = await deleteProduct(data.id);
            if (resp) {
              onlyMessage('操作成功！', 'success');
              tableRef.value?.reload();
            } else {
              onlyMessage('操作失败！', 'error');
            }
          }
        },
        icon: 'DeleteOutlined'
      }
    ];
    if (type === 'card') return actions.filter((i: any) => i.key !== 'view');
    return actions;
  };

  /**
   * 新增
   */
  const add = () => {
    isAdd.value = 1;
    title.value = '新增';
    saveShow.value = true;
    nextTick(() => {
      saveRef.value.show({});
    });
  };

  /**
   * 导入
   */
  // const beforeUpload = (file: any) => {
  //   const reader = new FileReader();
  //   reader.readAsText(file);
  //   reader.onload = async (result) => {
  //     const text: any = result.target?.result || '{}';
  //     if (!file.type.includes('json')) {
  //       onlyMessage('请上传json格式文件', 'error');
  //       return false;
  //     }
  //     try {
  //       const data = JSON.parse(text || '{}');
  //       // 设置导入的产品状态为未发布
  //       data.state = 0;
  //       if (Array.isArray(data)) {
  //         onlyMessage('请上传json格式文件', 'error');
  //         return false;
  //       }
  //       delete data.state;
  //       const res = await updateDevice(data);
  //       if (res.code === 200) {
  //         onlyMessage('操作成功', 'success');
  //         tableRef.value?.reload();
  //       }
  //       return true;
  //     } catch {
  //       // message.error('请上传json格式文件');
  //     }
  //     return true;
  //   };
  //   return false;
  // };
  /**
   * 查看
   */
  const handleView = (id: string) => {
    productId.value = id;
    nextTick(() => {
      visible.value = true;
    });
  };

  /**
   * 刷新数据
   */
  const refresh = () => {
    tableRef.value?.reload();
  };
  const tableRef = ref<Record<string, any>>({});
  const saveRef = ref();
  const handleSearch = (e: any) => {
    params.value = e;
  };
  const goBack = () => {
    visible.value = true;
    nextTick(() => {
      visible.value = false;
    });
  };
  provide('goBack', goBack);
</script>

<style lang="less" scoped>
  .productImg {
    width: 80px;
    height: 80px;
  }
  .productName {
    white-space: nowrap; /*强制在同一行内显示所有文本，直到文本结束或者遭遇br标签对象才换行。*/
    overflow: hidden; /*超出部分隐藏*/
    text-overflow: ellipsis; /*隐藏部分以省略号代替*/
  }
  :deep(.card .card-warp .card-content) {
    padding: 28px 12px 28px 30px;
  }
  :deep(.jtable-card) {
    min-height: 597px;
  }
  :deep(.ant-pagination-options) {
    display: none;
  }
  ant-pagination .ant-pagination-item {
    min-width: 22px;
    height: 22px;
    line-height: 22px;
  }
</style>
