<template>
  <PageContainer>
    <div>
      <div class="state-container">
        <div class="state-body" v-for="item in stateList" :key="item.key">
          <div class="state-content">
            <div class="state-header">
              <div class="state-title">
                <JBadge :text="item.name" :color="colorMap.get(item.key)" />
              </div>

              <div class="state-title-right">
                <div class="state-button">
                  <PermissionButton
                    type="link"
                    v-if="item.key === 'failed' && stateInfo?.mode?.value === 'push'"
                    hasPermission="device/Firmware:update"
                    :popConfirm="{
                      title: `确定批量重试`,
                      onConfirm: confirm
                    }"
                  >
                    批量重试
                  </PermissionButton>
                </div>

                <div class="img">
                  <img :src="buttonImg" @click="handleRefresh(item.key)" alt="task" />
                </div>
              </div>
            </div>
            <div class="state-box">
              <div class="state-left" :style="`color: ${colorMap.get(item.key)}`">
                {{ state[item.key] }}
              </div>
              <img class="state-right" :src="item.img" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template>
    </BasicTable>
    <Save :data="current" v-if="visible" @change="saveChange" />
  </PageContainer>
</template>
<script lang="ts" setup name="TaskDetailPage">
  import { onMounted } from 'vue';
  import { historyCount, startTask } from '../../../../../api/device/firmware';
  import { getImage } from '@jdlinker/utils';
  import { cloneDeep } from 'lodash-es';
  import Save from './Save.vue';
  import { onlyMessage } from '@jdlinker/utils';
  import { ref } from 'vue';
  import { BasicTable, TableAction, PermissionButton, useListPage } from '@jdlinker/ui';
  import { columns, searchFormSchema } from './data';
  import { list } from './service';
  import { useRoute } from 'vue-router';
  // @ts-ignore
  import { PageContainer, Badge as JBadge } from 'linker-ui-components';
  //注册model
  //注册table数据
  const { tableContext } = useListPage({
    tableProps: {
      api: list,
      columns,
      formConfig: {
        schemas: searchFormSchema,
        fieldMapToNumber: [],
        fieldMapToTime: []
      }
    }
  });

  const [registerTable] = tableContext;
  const tableRef = ref<Record<string, any>>({});
  const route = useRoute();
  // const params = ref<Record<string, any>>({});
  const taskId = route.params?.id as string;
  const visible = ref(false);
  const current = ref({});
  // const productOptions = ref([]);

  const colorMap = new Map();
  colorMap.set('waiting', '#FF9000');
  colorMap.set('processing', '#4293FF');
  colorMap.set('failed', '#F76F5D');
  colorMap.set('success', '#24B276');
  colorMap.set('canceled', '#999');

  const stateList = [
    {
      key: 'waiting',
      name: '等待升级',
      img: getImage('/firmware/waiting.png')
    },
    {
      key: 'processing',
      name: '升级中',
      img: getImage('/firmware/loading.png')
    },
    {
      key: 'success',
      name: '升级完成',
      img: getImage('/firmware/finish.png')
    },
    {
      key: 'failed',
      name: '升级失败',
      img: getImage('/firmware/error.png')
    },
    {
      key: 'canceled',
      name: '已停止',
      img: getImage('/firmware/cancel.png')
    }
  ];

  const buttonImg = getImage('/firmware/button.png');
  const state = ref({
    waiting: 0,
    processing: 0,
    success: 0,
    failed: 0,
    canceled: 0
  });
  const stateInfo = ref();

  const defaultParams = [
    {
      terms: [
        {
          column: 'taskId',
          value: taskId
        }
      ]
    }
  ];

  const saveChange = (value: boolean) => {
    visible.value = false;
    current.value = {};
  };
  const confirm = async (e: MouseEvent) => {
    const res = await startTask(taskId, ['failed']);
    if (res.success) {
      onlyMessage('操作成功', 'success');
      handleRefresh('failed');
      tableRef.value.reload();
    }
  };

  const handleRefresh = async (key: string) => {
    const terms = cloneDeep(defaultParams);
    terms[0].terms.push({ column: 'state', value: key });
    const res = await historyCount({ terms });
    if (res.success) {
      state.value[key] = res?.result || 0;
    }
  };

  onMounted(() => {
    stateList.forEach((item) => {
      // handleRefresh(item.key);
    });
    // taskById(taskId).then((res) => {
    //   if (res.success) {
    //     stateInfo.value = res?.result;
    //   }
    // });
  });

  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        icon: 'clarity:note-edit-line',
        tooltip: '编辑'
        // onClick: handleEdit.bind(null, record),
      },
      {
        icon: 'clarity:info-standard-line',
        tooltip: '详情'
        // onClick: handleDetail.bind(null, record),
      }
    ];
  }
</script>

<style lang="less" scoped>
  .state-container {
    width: 100%;
    min-height: 148px;
    background-color: #ffffff;
    padding: 24px 12px;
    display: flex;
    flex-wrap: wrap;
    .state-body {
      background: linear-gradient(135.62deg, #f6f7fd 22.27%, rgba(255, 255, 255, 0.86) 91.82%);
      min-width: 185px;
      max-width: 580px;
      flex: 1px;
      margin: 0 12px;
      .state-content {
        width: 100% -15px;
        height: 100%;
        margin: 15px 0 0 15px;
        align-content: center;

        .state-header {
          display: flex;
          justify-content: space-between;
          height: 22px;
          .state-title-right {
            z-index: 1;
            display: flex;
            .img {
              width: 22px;
              margin: 0 10px;
              cursor: pointer;
              img {
                width: 22px;
                margin-top: -5px;
              }
            }
            .img:active {
              border: 1px #40a9ff solid;
            }
          }
        }
        .state-box {
          display: flex;
          justify-content: space-between;
          .state-left {
            flex: 1;
            font-size: 52px;
          }
          .state-right {
            height: 100%;
            flex: 1;
            margin-top: -31px;
            max-width: 120px;
            max-height: 94px;
          }
        }
      }
    }
  }
  .state-button {
    margin-top: -5px;
    margin-right: -12px;
  }
  //:deep(.jeecg-layout-content .full) {
  //  padding: 10px;
  //}
  :deep(.jeecg-basic-table) {
    height: auto;
  }
</style>
