<template>
  <div
    class="typesetting-management card flex flex-gap-10 h-100 overflow-hidden"
  >
    <div class="left-status">
      <ElTree
        ref="treeRef"
        default-expand-all
        :expand-on-click-node="false"
        :default-expanded-keys="[]"
        :highlight-current="true"
        node-key="statusCode"
        :data="treeData"
        @node-click="nodeClick"
      >
        <template #default="{ data }">
          <div class="tree-node">
            <div class="tree-node-label">{{ data.statusName }}</div>
            <div class="tree-node-count">{{ `(${data.quantity})` }}</div>
          </div>
        </template>
      </ElTree>
    </div>
    <div class="right-content flex-1 flex-column overflow-hidden">
      <div class="search-form">
        <ElForm
          :model="searchForm"
          size="large"
          inline
          @submit.prevent
          @keyup.enter="search"
        >
          <!-- <ElFormItem label="创建时间" prop="rangeDate">
            <ElDatePicker
              v-model="searchForm.rangeDate"
              type="datetimerange"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 300px;"
            ></ElDatePicker>
          </ElFormItem> -->
          <ElFormItem label="ID" prop="sku">
            <ElInput
              v-model="searchForm.sku"
              clearable
              placeholder="ID"
              style="width: 160px"
            ></ElInput>
          </ElFormItem>
          <!-- <ElFormItem label="商品名称" prop="productName">
            <ElInput
              v-model="searchForm.productName"
              clearable
              placeholder="商品名称"
              style="width: 160px"
            ></ElInput>
          </ElFormItem> -->
          <ElFormItem>
            <ElButton type="primary" size="large" @click="search"
              >查询</ElButton
            >
          </ElFormItem>
          <ElFormItem v-if="treeId === '201'">
            <el-button size="large" type="danger" @click="reject"
              >驳回</el-button
            >
          </ElFormItem>
        </ElForm>
      </div>
      <div v-if="cardList.length" class="card-mode">
        <div v-loading="loading" class="card-list">
          <div
            v-for="cardItem in cardList"
            :key="cardItem.id"
            class="card-list_item"
            @click="cardClick(cardItem)"
          >
            <CommonCard
              :card-item="cardItem"
              :active="isSelectStatused(cardItem)"
              :show-sku="true"
              :show-product-info="true"
              :show-image-list="true"
              image-field="mainImage"
            >
              <template #productName>
                <span class="commodity-card-name">{{
                  cardItem.productName
                }}</span>
              </template>
              <template v-if="cardItem.retailPrice" #price>
                <span class="price">
                  {{ cardItem.retailPrice ? '$' : ''
                  }}{{ cardItem.retailPrice }}
                </span>
              </template>
              <template #operations>
                <Icon name="caozuorizhi" @click.stop="operationLog(cardItem)">
                  <template #title>
                    <title>操作日志</title>
                  </template>
                </Icon>
                <span
                  v-if="['201', '401'].includes(treeId) && cardItem.paperFile"
                  class="download-icon"
                  title="点击下载"
                  @click.stop="downloadFile(cardItem)"
                >
                  <svg
                    t="1741336618712"
                    class="icon"
                    viewBox="0 0 1024 1024"
                    version="1.1"
                    xmlns="http://www.w3.org/2000/svg"
                    p-id="3070"
                    width="22"
                    height="22"
                  >
                    <path
                      d="M821.76 374.72a43.328 43.328 0 0 0-30.976 13.504l-256.64 261.12c-11.072 11.264-33.28 11.264-44.288 0l-256.64-261.12a42.24 42.24 0 0 0-61.952 0 44.032 44.032 0 0 0 0 63.04l256.64 261.056c22.144 22.464 53.12 35.968 84.096 35.968 33.28 0 61.952-13.44 86.272-35.968l256.704-261.12a44.032 44.032 0 0 0 0-62.976c-11.072-8.96-22.08-13.504-33.216-13.504zM512 73.152a44.8 44.8 0 0 0-44.288 44.992v585.152a44.8 44.8 0 0 0 44.288 44.992 44.8 44.8 0 0 0 44.288-44.992V118.144A44.8 44.8 0 0 0 512 73.152z m331.904 787.648H180.096a44.8 44.8 0 0 0-44.288 45.056 44.8 44.8 0 0 0 44.288 44.992h663.808a44.8 44.8 0 0 0 44.288-44.992 44.8 44.8 0 0 0-44.288-45.056z"
                      fill="#ffffff"
                      p-id="3071"
                    ></path>
                  </svg>
                </span>
                <Icon
                  name="chakanxiangqing"
                  @click.stop="submitReview(cardItem, true)"
                >
                  <template #title>
                    <title>查看详情</title>
                  </template>
                </Icon>
                <Icon
                  v-if="treeId === '201'"
                  name="querenshenhexunjia"
                  @click.stop="confirm(cardItem)"
                >
                  <template #title>
                    <title>确认</title>
                  </template>
                </Icon>
                <Icon
                  v-if="treeId === '301' || treeId === '401'"
                  name="shenhe2"
                  @click.stop="submitReview(cardItem)"
                >
                  <template #title>
                    <title>
                      {{
                        cardItem?.state === '301'
                          ? '打版完成'
                          : cardItem?.state === '401'
                          ? '修改'
                          : ''
                      }}
                    </title>
                  </template>
                </Icon>
                <Icon
                  v-if="treeId === '601'"
                  name="baojiachaxun"
                  @click.stop="submitReview(cardItem)"
                >
                  <template #title>
                    <title>上传稿件</title>
                  </template>
                </Icon>
              </template>
              <template #time>
                <div class="product-time">
                  <div class="create-time">
                    <span class="label">创建时间:</span>
                    <span class="value">{{ cardItem.createTime }}</span>
                  </div>
                  <div class="assign-time">
                    <span class="label">分派时间:</span>
                    <span class="value">{{ cardItem.assignmentTime }}</span>
                  </div>
                </div>
              </template>
            </CommonCard>
          </div>
        </div>
      </div>
      <div v-else class="no-data">暂无数据</div>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[100, 200, 300, 400, 500]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin: 10px auto 10px; text-align: right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 确认 -->
    <reviewModel
      ref="reviewModal"
      v-model="reviewVisible"
      v-model:row="row"
      title="确认"
      @refresh="onRefreshPage"
    />
    <!-- 提交审核 -->
    <submitReviewModal
      ref="submitReviewModelRef"
      v-model="submitReviewVisible"
      :detailable="detailable"
      :title="
        detailable
          ? '查看详情'
          : row?.state === '301'
          ? '打版完成'
          : row?.state === '401'
          ? '修改'
          : '上传稿件'
      "
      :row="row"
      @refresh="onRefreshPage"
    ></submitReviewModal>
    <!-- 操作日志 -->
    <ElDialog
      v-model="logVisible"
      title="操作日志"
      width="700px"
      :close-on-click-modal="false"
    >
      <template #default>
        <div
          class="log-list"
          style="color: #333; height: 400px; overflow: auto"
        >
          <div v-for="(item, index) in logList" :key="index" class="log-item">
            <div class="icon-left">
              <Icon name="a-2labadianji3x" />
              <span class="time">{{ item.createTime }}</span
              >&emsp;
            </div>
            <span class="description" :title="item.description">
              {{ item.description }}
            </span>
          </div>
        </div>
      </template>
    </ElDialog>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import type {
  TreeData,
  SearchForm,
  TypesettingListData,
  LogList,
} from '@/types/api/typesetting'
import { useValue } from '@/utils/hooks/useValue'
import usePageList from '@/utils/hooks/usePageList'
import {
  getTypeListApi,
  getStatusListApi,
  getTypesettingDetail,
  getTypesettingLogByIdApi,
  rejectDataApi,
} from '@/api/typesetting'
import Icon from '@/components/Icon.vue'
import reviewModel from './reviewModel.vue'
import submitReviewModal from './submitReviewModal.vue'
import dayjs from 'dayjs'
import { showConfirm } from '@/utils/ui'
import CommonCard from '@/components/CommonCard.vue'
const treeData = ref<TreeData[]>([])
const treeRef = ref()
const treeId = ref('201')
const [searchForm] = useValue<SearchForm>({
  pageSize: 20,
  currentPage: 1,
  sku: '',
})
const downloadFile = (item: TypesettingListData) => {
  if (item.paperFile) {
    window.open(item.paperFile)
  }
}
const getStatusList = async () => {
  try {
    const res = await getStatusListApi()
    treeData.value = res.data.slice(0, 1)
    treeData.value[0].children = res.data.slice(1)
    nextTick(() => {
      treeRef.value.setCurrentKey(treeId.value, true)
    })
  } catch (e) {
    console.error(e)
  }
}
onMounted(() => {
  getStatusList()
})
const nodeClick = (data: TreeData) => {
  treeId.value = data.statusCode
  selection.value = []
  refresh()
}
const onRefreshPage = () => {
  refresh()
  getStatusList()
}
const {
  loading,
  currentPage,
  pageSize,
  total,
  onCurrentPageChange: handleSizeChange,
  onPageSizeChange: handleCurrentChange,
  refresh,
  data: cardList,
} = usePageList({
  query: (page, pageSize) =>
    getTypeListApi(
      { ...searchForm.value, state: treeId.value },
      page,
      pageSize,
    ).then((res) => res.data),
})
const search = () => {
  refresh()
}
const selection = ref<TypesettingListData[]>([])
const cardClick = (data: TypesettingListData) => {
  const status = isSelectStatused(data)
  if (status) {
    selection.value = selection.value.filter((item) => item.id !== data.id)
  } else {
    selection.value.push(data)
  }
}
const isSelectStatused = (data: TypesettingListData) => {
  const index = selection.value.findIndex((item) => item.id === data.id)
  return index !== -1
}
const reviewModal = ref()
const reviewVisible = ref(false)
const row = ref<TypesettingListData>()
const confirm = async (data: TypesettingListData) => {
  try {
    const res = await getTypesettingDetail(data.id)
    row.value = res.data
    reviewVisible.value = true
    nextTick(() => {
      reviewModal.value?.refreshForm()
    })
  } catch (e) {
    console.error(e)
  }
}
const submitReviewVisible = ref(false)
const submitReviewModelRef = ref()
const detailable = ref(false)
const submitReview = async (data: TypesettingListData, isDetail = false) => {
  detailable.value = isDetail
  try {
    submitReviewModelRef.value?.getExamineInfo(data)
    if (data.state === '601' || data.state === '701' || data.state === '901') {
      submitReviewModelRef.value?.getPriceDetail(data)
    }
    const res = await getTypesettingDetail(data.id)
    row.value = res.data
    nextTick(() => {
      submitReviewModelRef.value?.reset()
    })
    submitReviewVisible.value = true
  } catch (e) {
    console.error(e)
  }
}
const logList = ref<LogList[]>([])
const logVisible = ref(false)
const operationLog = async (data: TypesettingListData) => {
  try {
    const res = await getTypesettingLogByIdApi(data.id)
    res.data.forEach((item) => {
      item.createTime = dayjs(item.createTime).format('YYYY-MM-DD HH:mm:ss')
    })
    logList.value = res.data
    logVisible.value = true
  } catch (e) {
    console.error(e)
  }
}
const reject = async () => {
  if (!selection.value.length) {
    return ElMessage.warning('请选择要驳回的数据')
  }
  try {
    await showConfirm('确定驳回吗?', {
      type: 'warning',
      confirmButtonText: '确认',
      cancelButtonText: '取消',
    })
  } catch {
    return
  }
  const ids = selection.value.map((item) => item.id).join(',')
  try {
    const res = await rejectDataApi(ids)
    ElMessage.success(res.message)
    onRefreshPage()
  } catch (e) {
    console.error(e)
  }
}
</script>
<style lang="scss" scoped>
.left-status {
  width: 160px;
  :deep(.el-tree-node__content) {
    height: 30px;
    line-height: 30px;
  }
  :deep(.el-tree-node__label) {
    font-size: 13px;
    cursor: pointer;
    display: inline-block;
    width: 100%;
    color: black !important;

    padding: 3px 7px;
  }

  :deep(.el-tree-node__expand-icon) {
    display: none;
  }

  :deep(.is-current) {
    .tree-node-label,
    .tree-node-count {
      background-color: #ecf5ff;
      color: #409eff !important;
    }

    .el-tree-node__children {
      .tree-node-label,
      .tree-node-count {
        background-color: transparent !important;
        color: black !important;
      }
    }
  }
}

.tree-node {
  display: flex;
  color: #333;
  font-weight: 500;
}
.card-mode {
  flex: 1;
  overflow: auto;
}
.card-list {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  grid-template-rows: max-content;
  gap: 10px;
}
.card-list_item {
  border: 1px solid #eee;
  border-top-left-radius: 10px;
  background-color: #eee;
  overflow: hidden;
  cursor: pointer;
  .download-icon {
    display: inline-block;
    line-height: 32px;
    background: #554598;
    width: 32px;
    height: 32px;
    border-radius: 10px;
    margin-left: 5px;
  }
}

.price {
  color: rgba(181, 124, 91, 1);
  font-weight: 600;
}
.no-data {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #777;
}
.log-item {
  width: 560px;
  display: flex;
  align-items: center;
  .icon-left {
    width: 172px;
    display: flex;
    align-items: center;
    margin-right: 20px;
    white-space: nowrap;
  }
  .time {
    // width: 150px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .description {
    display: inline-block;
    flex: 1;
    word-wrap: break-word;
    cursor: pointer;
  }
}

.svg-icon {
  margin-left: 5px;
}

.product-time {
  margin-bottom: 10px;
  .create-time,
  .assign-time {
    height: 26px;
    line-height: 26px;
  }
}
</style>
