<script setup>
import { getScoreDetail, updateScore } from '../api'
import { useMapStore } from '@/stores/map'
import {
  getNameByValue,
  importType,
  requiredType,
  deliveryMode,
  deliveryTime,
  shippingTemplate,
  afterSalesPolicy,
} from '@/utils/dictionary'
import ScoreCard from '../components/ScoreCard.vue'
import ScoreCardLive from '../components/ScoreCardLive.vue'
import Preview from '@/components/Preview.vue'
import { ElMessageBox } from 'element-plus'

const route = useRoute()
const id = route.query.id

const statusList = useMapStore().getMapValuesByKey('system_status')

const detail = ref(null)

const scoreDetails = reactive({
  commodity_type: { score: null, comment: '' },
  commodity_attr: { score: null, comment: '' },
  commodity: { score: null, comment: '' },
  speech: { score: null, comment: '' },
  practice_record1: { score: null, comment: '' },
  improvement_plan: { score: null, comment: '' },
  practice_record2: { score: null, comment: '' },
  report: { score: null, comment: '' },
})

const totalScore = computed(() => {
  return Object.values(scoreDetails).reduce((acc, curr) => acc + (curr.score || 0), 0)
})

const fetchDetail = async () => {
  const res = await getScoreDetail({ id })
  detail.value = res.data.detail
  Object.assign(scoreDetails, res.data.detail.score_details ? JSON.parse(res.data.detail.score_details) : {})
}

onMounted(() => {
  fetchDetail()
})

// 商品类别
const categoryTableOptions = {
  columns: [
    { label: '商品品类名称', prop: 'name', align: 'left' },
    { label: '层级', prop: 'level' },
    {
      label: '状态',
      prop: 'status',
      computed({ row }) {
        const color = row.status === '1' ? 'var(--main-success-color)' : 'var(--main-color)'
        return `<span style="color: ${color}">${getNameByValue(row.status, statusList)}</span>`
      },
    },
  ],
}

// 商品属性
const attrsTableOptions = {
  columns: [
    { label: '序号', type: 'index', width: 60 },
    { label: '商品属性名称', prop: 'name' },
    { label: '所属商品品类', prop: 'live_commodity_type_full_name' },
    {
      label: '重要性',
      prop: 'is_importance',
      computed({ row }) {
        return getNameByValue(row.is_importance, importType)
      },
    },
    {
      label: '必要性',
      prop: 'is_essential',
      computed({ row }) {
        return getNameByValue(row.is_essential, requiredType)
      },
    },
    {
      label: '状态',
      prop: 'status',
      computed({ row }) {
        const color = row.status === '1' ? 'var(--main-success-color)' : 'var(--main-color)'
        return `<span style="color: ${color}">${getNameByValue(row.status, statusList)}</span>`
      },
    },
    { label: '更新时间', prop: 'updated_time' },
  ],
}

// 商品管理
const productList = computed(() => {
  return detail.value.live_data?.commodities?.map((item) => {
    try {
      item.info = JSON.parse(item.info)
      item.live_commodity_attrs = JSON.parse(item.live_commodity_attrs)
      item.picture_34_addreses = JSON.parse(item.picture_34_addreses)
      item.picture_addreses = JSON.parse(item.picture_addreses)
    } catch (error) {
      console.log(error)
    }
    console.log(item)
    return item
  })
})
const productTableOptions = {
  columns: [
    {
      type: 'expand',
      slots: 'table-expand',
    },
    { label: '序号', type: 'index', width: 60 },
    { label: '商品标题', prop: 'title' },
    { label: '所属商品品类', prop: 'live_commodity_type_full_name' },
    { label: '参考价(¥)', prop: 'info.reference_price' },
    {
      label: '发货模式',
      prop: 'delivery_mode',
      computed({ row }) {
        return getNameByValue(row.info.delivery_mode, deliveryMode)
      },
    },
    {
      label: '发货时效',
      prop: 'delivery_time',
      computed({ row }) {
        return getNameByValue(row.info.delivery_time, deliveryTime)
      },
    },
    {
      label: '运费模板',
      prop: 'shipping_template',
      computed({ row }) {
        return getNameByValue(row.info.shipping_template, shippingTemplate)
      },
    },
    {
      label: '售后政策',
      prop: 'after_sales_policy',
      computed({ row }) {
        return getNameByValue(row.info.after_sales_policy, afterSalesPolicy)
      },
    },
  ],
}
// 商品规格
const productSpecsTableOptions = {
  columns: [
    { label: '规格名称', prop: 'name' },
    {
      label: '规格值',
      prop: 'value',
      computed({ row }) {
        return row.values.join(' / ')
      },
    },
  ],
}
// 商品sku
const productSkuTableOptions = {
  columns: [
    {
      label: '规格',
      prop: 'name',
      computed({ row }) {
        return row.specs.join(' / ')
      },
    },
    { label: '价格(¥)', prop: 'price' },
    { label: '库存', prop: 'stock' },
  ],
}

// 直播话术
const talkTableOptions = {
  columns: [
    { type: 'expand', slots: 'table-expand' },
    { label: '序号', type: 'index', width: 60 },
    { label: '直播话术名称', prop: 'name' },
    { label: '直播主题标题', prop: 'live_commodity_title' },
    {
      label: '话术时长',
      prop: 'duration',
      computed({ row }) {
        return `${row.duration}分钟`
      },
    },
    { label: '所属直播主题品类', prop: 'live_commodity_type_full_name' },
  ],
}
const activeTab = ref(1)

const handleAIScore = () => {
  console.log('AI一键评分')
}

const handleSave = (key, params) => {
  scoreDetails[key] = params
  commitScore(0).then(() => {
    ElMessage.success('保存成功')
  })
}
const handleNext = () => {
  activeTab.value++
}

const commitScore = (status = 0) => {
  return updateScore({
    id: route.query.id,
    score_status: status,
    total_score: totalScore.value,
    score_details: JSON.stringify(scoreDetails),
  })
}

const handlePublishScore = () => {
  ElMessageBox.confirm('确定要发布成绩吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await commitScore(1)
    await fetchDetail()
    ElMessage.success('发布成绩成功')
  })
}
</script>
<template>
  <AppCard title="直播成绩管理" v-if="detail">
    <div class="score-header">
      <el-form label-suffix=":" inline class="info">
        <el-form-item label="姓名">{{ detail.student_name }}</el-form-item>
        <el-form-item label="专业">{{ detail.specialty_name }}</el-form-item>
        <el-form-item label="班级">{{ detail.class_name }}</el-form-item>
        <el-form-item label="状态">{{ detail.status_name }}</el-form-item>
        <el-form-item label="提交时间">{{ detail.commit_time }}</el-form-item>
        <el-form-item>
          <el-button type="primary" :disabled="detail.status == '2'" @click="handleAIScore">AI一键评分</el-button>
          <el-button type="primary" :disabled="detail.status == '2'" @click="handlePublishScore">发布成绩</el-button>
        </el-form-item>
      </el-form>
      <div class="score-box">
        <span>{{ totalScore || '--' }}分</span>
      </div>
    </div>
    <el-divider />
    <el-tabs stretch v-model="activeTab" class="score-tabs">
      <el-tab-pane label="商品品类管理" :name="1">
        <ScoreCard
          :maxScore="5"
          :hasSaveButton="detail.status != '2'"
          :score="scoreDetails.commodity_type.score"
          :comment="scoreDetails.commodity_type.comment"
          @save="handleSave('commodity_type', $event)"
          @next="handleNext">
          <AppList v-bind="categoryTableOptions" row-key="id" :data="detail.live_data.commodity_types" />
        </ScoreCard>
      </el-tab-pane>
      <el-tab-pane label="商品属性管理" :name="2" lazy>
        <ScoreCard
          :maxScore="5"
          :hasSaveButton="detail.status != '2'"
          :score="scoreDetails.commodity_attr.score"
          :comment="scoreDetails.commodity_attr.comment"
          @save="handleSave('commodity_attr', $event)"
          @next="handleNext">
          <AppList v-bind="attrsTableOptions" :data="detail.live_data.commodity_attrs" />
        </ScoreCard>
      </el-tab-pane>
      <el-tab-pane label="商品管理" :name="3" lazy>
        <ScoreCard
          :maxScore="15"
          :hasSaveButton="detail.status != '2'"
          :score="scoreDetails.commodity.score"
          :comment="scoreDetails.commodity.comment"
          @save="handleSave('commodity', $event)"
          @next="handleNext">
          <AppList v-bind="productTableOptions" :data="productList" :default-expand-all="productList.length === 1">
            <template #table-expand="{ row }">
              <div class="table-expand-box">
                <el-form label-position="top">
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="主图">
                        <el-image
                          :src="item.url"
                          v-for="item in row.picture_addreses"
                          :key="item.url"
                          fit="cover"
                          preview-teleported
                          :preview-src-list="row.picture_addreses.map((item) => item.url)"
                          style="width: 100px; height: 100px; margin-right: 10px"></el-image>
                      </el-form-item>
                      <el-form-item label="主图3:4">
                        <el-image
                          :src="item.url"
                          v-for="item in row.picture_34_addreses"
                          :key="item.url"
                          fit="cover"
                          preview-teleported
                          :preview-src-list="row.picture_addreses.map((item) => item.url)"
                          style="width: 100px; height: 134px; margin-right: 10px"></el-image>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="主图视频">
                        <video
                          :src="row.video_url"
                          controls
                          style="width: 100%; height: 282px"
                          v-if="row.video_url"></video>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-form-item label="商品规格">
                    <AppList v-bind="productSpecsTableOptions" :data="row.info?.specs" style="width: 100%"></AppList>
                  </el-form-item>
                  <el-form-item label="价格与库存">
                    <AppList v-bind="productSkuTableOptions" :data="row.info?.sku" style="width: 100%"></AppList>
                  </el-form-item>
                </el-form>
              </div>
            </template>
          </AppList>
        </ScoreCard>
      </el-tab-pane>
      <el-tab-pane label="直播话术管理" :name="4" lazy>
        <ScoreCard
          :maxScore="15"
          :hasSaveButton="detail.status != '2'"
          :score="scoreDetails.speech.score"
          :comment="scoreDetails.speech.comment"
          @save="handleSave('speech', $event)"
          @next="handleNext">
          <AppList
            v-bind="talkTableOptions"
            :data="detail.live_data.speeches"
            :default-expand-all="detail.live_data.speeches.length === 1">
            <template #table-expand="{ row }">
              <div class="table-expand-box">
                <el-form label-position="top">
                  <el-form-item label="直播主题卖点">
                    <div class="form-box" v-html="row.selling_point"></div>
                  </el-form-item>
                  <el-form-item label="营销活动">
                    <div class="form-box" v-html="row.marketing_campaign"></div>
                  </el-form-item>
                  <el-form-item label="直播话术内容">
                    <div class="form-box" v-html="row.content"></div>
                  </el-form-item>
                </el-form>
              </div>
            </template>
          </AppList>
        </ScoreCard>
      </el-tab-pane>
      <el-tab-pane label="首次直播演练" :name="5" lazy>
        <ScoreCard
          :maxScore="20"
          :hasSaveButton="detail.status != '2'"
          :score="scoreDetails.practice_record1.score"
          :comment="scoreDetails.practice_record1.comment"
          @save="handleSave('practice_record1', $event)"
          @next="handleNext">
          <ScoreCardLive :data="detail.live_data.practice_records[0]" v-if="detail.live_data.practice_records[0]" />
          <el-empty v-else />
        </ScoreCard>
      </el-tab-pane>
      <el-tab-pane label="直播复盘分析" :name="6" lazy>
        <ScoreCard
          :maxScore="10"
          :hasSaveButton="detail.status != '2'"
          :score="scoreDetails.improvement_plan.score"
          :comment="scoreDetails.improvement_plan.comment"
          @save="handleSave('improvement_plan', $event)"
          @next="handleNext">
          <el-form label-position="top" v-if="detail.live_data.practice_records[0]?.improvement_plan">
            <el-form-item label="改进方案">
              <div class="form-box" v-html="detail.live_data.practice_records[0]?.improvement_plan"></div>
            </el-form-item>
          </el-form>
          <el-empty v-else />
        </ScoreCard>
      </el-tab-pane>
      <el-tab-pane label="二次直播演练" :name="7" lazy>
        <ScoreCard
          :maxScore="15"
          :hasSaveButton="detail.status != '2'"
          :score="scoreDetails.practice_record2.score"
          :comment="scoreDetails.practice_record2.comment"
          @save="handleSave('practice_record2', $event)"
          @next="handleNext">
          <ScoreCardLive :data="detail.live_data.practice_records[1]" v-if="detail.live_data.practice_records[1]" />
          <el-empty v-else />
        </ScoreCard>
      </el-tab-pane>
      <el-tab-pane label="直播总结汇报" :name="8" lazy>
        <ScoreCard
          :maxScore="15"
          :hasSaveButton="detail.status != '2'"
          :hasNextButton="false"
          :score="scoreDetails.report.score"
          :comment="scoreDetails.report.comment"
          @save="handleSave('report', $event)"
          @next="handleNext">
          <template v-if="detail.live_data.reports.length > 0">
            <div v-for="item in detail.live_data.reports" :key="item.report_url">
              <Preview :url="item.report_url" />
            </div>
          </template>
          <el-empty v-else />
        </ScoreCard>
      </el-tab-pane>
    </el-tabs>
  </AppCard>
</template>

<style lang="scss" scoped>
.score-tabs {
  :deep(.el-tabs__header) {
    width: 1000px;
    margin: 0 auto 20px;
  }
  :deep(.el-tabs__nav-wrap::after) {
    display: none;
  }
}
.score-header {
  display: flex;
  align-items: center;
  .el-form {
    flex: 1;
  }
}
.score-box {
  width: 100px;
  border: 1px solid #dcdfe6;
  padding: 10px;
  border-radius: 10px;
  font-size: 30px;
  color: var(--main-color);
  display: flex;
  align-items: center;
  justify-content: center;
}
.table-expand-box {
  border: 1px solid #dcdfe6;
  padding: 20px;
  border-radius: 10px;
}
.form-box {
  width: 100%;
  border: 1px solid #dcdfe6;
  padding: 10px;
  border-radius: 6px;
}
</style>
