<template>
  <div class="index">
    <el-row>
      <el-col :span="24" class="main animate__animated animate__backInRight" v-loading="loading">
        <custom-form v-model="form" :fields="formFields" :rules="rules" @save="toSave" @draftSave="toDraftSave">
          <template #is_use>
            <el-radio v-for="i in isUseList" :key="i.id" :label="i.value">{{ i.label }}</el-radio>
          </template>
          <template #field>
            <el-option v-for="i in fieldList" :key="i.id" :label="i.label" :value="i.label"></el-option>
          </template>
          <template #attribute>
            <el-option v-for="i in attributeList" :key="i.id" :label="i.label" :value="i.value"></el-option>
          </template>
          <template #mature>
            <el-option v-for="i in matureList" :key="i.id" :label="i.label" :value="i.value"></el-option>
          </template>
          <template #sell>
            <el-option v-for="i in sellList" :key="i.id" :label="i.label" :value="i.value"></el-option>
          </template>
          <template #technology>
            <el-option v-for="i in technologyList" :key="i.id" :label="i.label" :value="i.value"></el-option>
          </template>
          <template #area>
            <el-cascader v-model="form.area" :props="{ value: 'name', label: 'name' }" :options="cityList" style="width: 100%" />
          </template>
          <template #file>
            <custom-upload model="file" :list="form.file" :limit="1" url="/files/web/cxyy_achievement/upload" @change="onUpload"></custom-upload>
          </template>
          <template #industry>
            <el-option v-for="i in sectorList" :key="i.id" :label="i.title" :value="i.title"></el-option>
          </template>
          <template #tags>
            <el-select v-model="form.tags" multiple filterable allow-create default-first-option :reserve-keyword="false" placeholder="请选择标签" style="width: 100%">
              <el-option v-for="item in tagsList" :key="item.id" :label="item.title" :value="item.title" />
            </el-select>
          </template>
        </custom-form>
      </el-col>
    </el-row>
    <el-dialog v-model="dialog.show" :title="dialog.title" :destroy-on-close="false" @close="toClose" :width="width">
      <el-row>
        <transition name="why">
          <el-col :span="24" v-if="dialog.type == '2'" class="dialog" v-loading="isLoading" element-loading-text="智能推荐中..." :element-loading-svg="svg" element-loading-svg-view-box="-10,-10,50,50">
            <el-empty v-if="demandtotal == 0" description="暂无数据" />
            <div class="list" v-for="(item, index) in demandList" :key="index" @click="toView(item)">
              <h2 class="name textMore">
                <span>{{ item.name || '暂无' }}</span>
              </h2>
              <div class="other">
                <span class="other_1">{{ getDict(item.urgent, 'urgent') || '暂无' }}</span>
                <div class="other_2">
                  <span>应用行业：</span>
                  {{ item.field || '暂无' }}
                </div>
                <div class="other_2">
                  <span>资金预算：</span>
                  {{ item.money || '面议' }}
                </div>
                <div class="other_2">
                  <span>推荐指数：</span>
                  <el-rate size="large" v-model="item._recommend" disabled show-score text-color="#ff9900" :score-template="`${item._recommend} 星`" />
                </div>
                <div class="other_2 textOne">
                  <el-icon color="#0085f5"><Location /></el-icon>
                  {{ getArea(item.area) }}
                  <span class="state">{{ getDict(item.status, 'status') || '未解决' }}</span>
                </div>
              </div>
            </div>
            <el-col :span="24" class="page">
              <el-pagination background layout="prev, pager, next" :total="demandtotal" :page-size="demandlimit" v-model:current-page="dcurrentPage" @current-change="dchangePage" @size-change="dsizeChange" />
            </el-col>
          </el-col>
        </transition>
      </el-row>
    </el-dialog>
  </div>
</template>

<script setup>
const router = useRouter()
import { cloneDeep, get } from 'lodash-es'
const $checkRes = inject('$checkRes')
import { UserStore } from '@/store/user'
const userStore = UserStore()
const user = computed(() => userStore.user)
// 接口
import { AchievementStore } from '@/store/api/platform/achievement'
import { DictDataStore } from '@/store/api/system/dictData'
import { TagsStore } from '@/store/api/system/tags'
import { SectorStore } from '@/store/api/platform/sector'
import { RegionStore } from '@/store/api/system/region'
import { EsStore } from '@/store/api/es'
const esStore = EsStore()
const regionStore = RegionStore()
const store = AchievementStore()
const dictDataStore = DictDataStore()
const tagsStore = TagsStore()
const sectorStore = SectorStore()
// 加载中
const loading = ref(false)
// 字典表
const isUseList = ref([])
const statusList = ref([])
const fieldList = ref([])
const attributeList = ref([])
const matureList = ref([])
const sellList = ref([])
const technologyList = ref([])
const cityList = ref([])
const achievementList = ref([])
const tagsList = ref([])
const sectorList = ref([])
const urgentList = ref([])
const formFields = ref([
  { label: '成果名称', model: 'name' },
  { label: '标签', model: 'tags', custom: true, mark: 'tags' },
  { label: '所属产业', model: 'industry', type: 'select' },
  { label: '专利号', model: 'patent' },
  { label: '行业领域', model: 'field' },
  { label: '属性', model: 'attribute', type: 'select', mark: 'dict', code: 'attribute' },
  { label: '成熟度', model: 'mature', type: 'select', mark: 'dict', code: 'mature' },
  { label: '出让方式', model: 'sell', type: 'select', mark: 'dict', code: 'sell' },
  { label: '技术分类', model: 'technology', type: 'select', mark: 'dict', code: 'technology' },
  { label: '成果地区', model: 'area', custom: true, mark: 'area' },
  { label: '发布时间', model: 'time', type: 'date' },
  { label: '价格(万元)', model: 'money' },
  { label: '项目来源', model: 'source' },
  { label: '联系人', model: 'person' },
  { label: '联系电话', model: 'tel' },
  { label: '是否公开', model: 'is_use', type: 'radio', mark: 'dict', code: 'isUse' },
  { label: '简介', model: 'brief', type: 'textarea' },
  { label: '附件', model: 'file', custom: true, mark: 'file' }
])
const form = ref({ file: [] })
const rules = reactive({
  name: [{ required: true, message: '请输入成果名称', trigger: 'blur' }],
  field: [{ required: true, message: '请输入行业领域', trigger: 'blur' }],
  attribute: [{ required: true, message: '请选择属性', trigger: 'blur' }],
  mature: [{ required: true, message: '请选择成熟度', trigger: 'blur' }],
  sell: [{ required: true, message: '请选择出让方式', trigger: 'blur' }],
  technology: [{ required: true, message: '请选择技术分类', trigger: 'blur' }],
  area: [{ required: true, message: '请选择成果地区', trigger: 'blur' }],
  time: [{ required: true, message: '请选择发布时间', trigger: 'blur' }],
  money: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  source: [{ required: true, message: '请输入项目来源', trigger: 'blur' }],
  person: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  tel: [{ required: true, message: '请输入联系电话', trigger: 'blur' }]
})
// 加载中
const isLoading = ref(false)
const svg = ref(`
          <path class="path" d="
            M 30 15
            L 28 17
            M 25.61 25.61
            A 15 15, 0, 0, 1, 15 30
            A 15 15, 0, 1, 1, 27.99 7.5
            L 15 15
          " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
        `)
// 推荐需求列表
const demandList = ref([])
let demandskip = 0
let demandlimit = 4
const demandtotal = ref(0)
const key = ref('')
const width = ref('50%')
const dialog = ref({ type: '1', show: false, title: '需求智能推荐' })
// 请求
onMounted(async () => {
  loading.value = true
  await searchOther()
  loading.value = false
})
const searchOther = async () => {
  let result
  // 是否使用
  result = await dictDataStore.query({ code: 'isUse', is_use: '0' })
  if ($checkRes(result)) isUseList.value = result.data
  // 状态
  result = await dictDataStore.query({ code: 'examStatus', is_use: '0' })
  if ($checkRes(result)) statusList.value = result.data
  // 成熟度
  result = await dictDataStore.query({ code: 'mature', is_use: '0' })
  if ($checkRes(result)) matureList.value = result.data
  // 出让方式
  result = await dictDataStore.query({ code: 'sell', is_use: '0' })
  if ($checkRes(result)) sellList.value = result.data
  // 技术领域
  result = await dictDataStore.query({ code: 'field', is_use: '0' })
  if ($checkRes(result)) fieldList.value = result.data
  // 属性
  result = await dictDataStore.query({ code: 'attribute', is_use: '0' })
  if ($checkRes(result)) attributeList.value = result.data
  // 技术分类
  result = await dictDataStore.query({ code: 'technology', is_use: '0' })
  if ($checkRes(result)) technologyList.value = result.data
  // 成果状态
  result = await dictDataStore.query({ code: 'demandStatus', is_use: '0' })
  if ($checkRes(result)) achievementList.value = result.data
  // 标签
  result = await tagsStore.query({ is_use: '0' })
  if ($checkRes(result)) tagsList.value = result.data
  // 行业
  result = await sectorStore.query({ is_use: '0' })
  if ($checkRes(result)) sectorList.value = result.data
  // 城市
  result = await regionStore.area({ level: 'province', code: 22 })
  if ($checkRes(result)) cityList.value = result.data
  // 需求紧急度
  result = await dictDataStore.query({ code: 'urgent', is_use: '0' })
  if ($checkRes(result)) urgentList.value = result.data
}
// 上传图片
const onUpload = (e) => {
  const { model, value } = e
  form.value[model] = value
}
const toSave = async () => {
  const data = cloneDeep(form.value)
  const other = { status: '0', user: user.value.id }
  let res
  if (get(data, 'id')) res = await store.update({ ...data, ...other })
  else res = await store.create({ ...data, ...other })
  if (res.errcode == 0) {
    ElMessage({ message: `发布成功可以上历史发布查看`, type: 'success' })
    key.value = form.value.name
    await toClose()
    await searchDemand({ demandskip, demandlimit })
    width.value = '90%'
    dialog.value = { type: '2', show: true, title: '相关需求推荐' }
  }
}
const toDraftSave = async () => {
  const data = cloneDeep(form.value)
  const other = { status: '-2', user: user.value.id }
  let res
  if (get(data, 'id')) res = await store.update({ ...data, ...other })
  else res = await store.create({ ...data, ...other })
  if (res.errcode == 0) {
    ElMessage({ message: `发布成功可以上历史发布查看`, type: 'success' })
    key.value = form.value.name
    await toClose()
    await searchDemand({ demandskip, demandlimit })
    width.value = '90%'
    dialog.value = { type: '2', show: true, title: '相关需求推荐' }
  }
}
const toClose = () => {
  form.value = {}
  width.value = '50%'
  dialog.value = { show: false }
}
// 地区
const getArea = (data) => {
  if (data) return data.join('-')
  else return '暂无地区'
}
// 字典数据转换
const getDict = (data, model) => {
  if (data) {
    let res
    if (model == 'status') res = statusList.value.find((f) => f.value == data)
    else if (model == 'urgent') res = urgentList.value.find((f) => f.value == data)
    return get(res, 'label')
  }
}
// 需求列表查询
const searchDemand = async (query = { demandskip, demandlimit }) => {
  demandskip = query.demandskip
  demandlimit = query.demandlimit
  isLoading.value = true
  const info = { skip: demandskip, limit: demandlimit, keyword: key.value }
  const res = await esStore.demand(info)
  if (res.errcode == '0') {
    demandList.value = res.data
    demandtotal.value = res.total
  }
  setTimeout(() => {
    isLoading.value = false
  }, 3000) // 假设3秒后加载完成
}
// 查看详情
const toView = (item) => {
  router.push({ path: '/demand/detail', query: { id: item.id || item._id } })
}
const dcurrentPage = ref(1)
// 分页
const dchangePage = (page = dcurrentPage.value) => {
  searchDemand({ demandskip: (page - 1) * demandlimit, demandlimit: demandlimit })
}
const dsizeChange = (limits) => {
  demandlimit = limits
  dcurrentPage.value = 1
  searchDemand({ demandskip: 0, demandlimit: demandlimit })
}
</script>
<style scoped lang="scss">
.why-enter-from,
.why-leave-to {
  opacity: 0;
  transform: scale(0.6);
}

.why-enter-to,
.why-leave-from {
  opacity: 1;
  transform: scale(1);
}

.why-enter-active,
.why-leave-active {
  transition: all 2s ease;
}
.dialog {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  margin-top: 20px;
  .list {
    position: relative;
    margin-right: 10px;
    margin-bottom: 10px;
    width: 380px;
    box-shadow: 0 0 13px 0 rgba(5, 88, 219, 0.18);
    .name {
      padding: 10px 20px;
      width: 380px;
      height: 71px;
      background-color: #dce5ff;
      font-size: 16px;
      line-height: 24px;
      color: #0d0d0d;
      display: flex;
      align-items: center;
    }
    .other {
      padding: 10px 20px 20px;
      .other_1 {
        padding: 0 10px;
        height: 25px;
        background-color: #e6f2fd;
        border-radius: 2px;
        border: solid 1px #cae0f5;
        font-size: $global-font-size-14;
        line-height: 25px;
        color: #0085f5;
      }
      .other_2 {
        display: flex;
        align-items: center;
        margin-top: 15px;
        font-size: $global-font-size-16;
        span {
          color: #909090;
        }
        .state {
          position: absolute;
          right: 20px;
          bottom: 15px;
          display: inline-block;
          vertical-align: middle;
          padding: 0 20px;
          height: 30px;
          line-height: 30px;
          background-image: linear-gradient(90deg, #ff8a00 0, #ff5a00 100%), linear-gradient(#ff7800, #ff7800);
          background-blend-mode: normal, normal;
          border-radius: 14px;
          border: solid 1px #e5e5e5;
          color: #fff;
        }
      }
    }
  }
  .list:hover {
    box-shadow: 0 0 5px 0 $global-color-107;
    .name {
      background-color: $global-color-107;
      color: $global-color-fff;
    }
  }
  .page {
    margin: 10px 0;
    display: flex;
    justify-content: center;
  }
}
</style>
