<template>
  <div class="index">
    <el-row>
      <el-col :span="24" class="main animate__animated animate__backInRight" v-loading="loading">
        <el-col :span="24" class="one">
          <div class="one_left" @click="toAdd">发布供给</div>
          <div class="one_right">
            <el-input v-model="searchForm.name" style="width: 250px" size="large" placeholder="搜索" @change="search" :suffix-icon="Search" />
          </div>
        </el-col>
        <el-col :span="24" class="two">
          <el-table :data="list" style="width: 100%" size="large" :header-cell-style="{ backgroundColor: '#edf3ff' }">
            <template #empty>
              <el-empty description="暂无数据" />
            </template>
            <el-table-column prop="name" align="center" label="供给名称" />
            <el-table-column prop="start_time" align="center" label="开始时间" width="180" />
            <el-table-column prop="end_time" align="center" label="结束时间" width="180" />
            <el-table-column prop="status" align="center" label="状态" width="180">
              <template #default="scope">
                <div>{{ getDict(scope.row.status, 'status') }}</div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="180">
              <template #default="{ row }">
                <el-link v-if="row.status == '-2'" :underline="false" type="warning" size="mini" @click="toExam(row)" style="margin-right: 10px">提交审核</el-link>
                <el-link :underline="false" type="primary" size="mini" @click="toEdit(row)" style="margin-right: 10px">修改</el-link>
                <el-link :underline="false" type="danger" size="mini" @click="toDelete(row)"> 删除 </el-link>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="24" class="thr">
          <el-pagination background layout="prev, pager, next" :total="total" :page-size="limit" v-model:current-page="currentPage" @current-change="changePage" @size-change="sizeChange" />
        </el-col>
      </el-col>
    </el-row>
    <el-dialog v-model="dialog.show" :title="dialog.title" :destroy-on-close="false" @close="toClose" :width="width">
      <el-row>
        <el-col :span="24" v-if="dialog.type == '1'">
          <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 #urgent>
              <el-option v-for="i in urgentList" :key="i.id" :label="i.label" :value="i.value"></el-option>
            </template>
            <template #method>
              <el-option v-for="i in methodList" :key="i.id" :label="i.label" :value="i.value"></el-option>
            </template>
            <template #industry>
              <el-option v-for="i in sectorList" :key="i.id" :label="i.title" :value="i.title"></el-option>
            </template>
            <template #area>
              <el-cascader v-model="form.area" :props="{ value: 'name', label: 'name' }" :options="cityList" style="width: 100%" />
            </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-col :span="24" v-if="dialog.type == '2'" class="dialog">
          <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 textOne">
                <el-icon color="#0085f5"><Location /></el-icon>
                {{ getArea(item.area) }}
                <span class="state">{{ getDict(item.status, 'status') || '未解决' }}</span>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script setup>
import { Search } from '@element-plus/icons-vue'
import { cloneDeep, get } from 'lodash-es'
const $checkRes = inject('$checkRes')
import { UserStore } from '@/store/user'
const userStore = UserStore()
const user = computed(() => userStore.user)
// 接口
import { SupplyStore } from '@/store/api/platform/supply'
import { DemandStore } from '@/store/api/platform/demand'
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'
const regionStore = RegionStore()
const store = SupplyStore()
const dictDataStore = DictDataStore()
const tagsStore = TagsStore()
const sectorStore = SectorStore()
const demandStore = DemandStore()
// 加载中
const loading = ref(false)
const router = useRouter()
const searchForm = ref({})
// 列表
const list = ref([])
let skip = 0
let limit = inject('limit')
const total = ref(0)
const currentPage = ref(1)
// 字典表
const isUseList = ref([])
const statusList = ref([])
const methodList = ref([])
const urgentList = ref([])
const fieldList = ref([])
const cityList = ref([])
const supplyList = ref([])
const tagsList = ref([])
const sectorList = ref([])

// 推荐需求列表
const demandList = ref([])
const width = ref('50%')

const form = ref({ time: [] })
const dialog = ref({ type: '1', show: false, title: '发布供给' })
const formFields = ref([
  { label: '供给名称', model: 'name' },
  { label: '标签', model: 'tags', custom: true },
  { label: '所属产业', model: 'industry', type: 'select' },
  { label: '行业领域', model: 'field' },
  { label: '供给紧急度', model: 'urgent', type: 'select' },
  { label: '合作方式', model: 'method', type: 'select' },
  { label: '价格(万元)', model: 'money' },
  { label: '项目来源', model: 'source' },
  { label: '供给地区', model: 'area', custom: true },
  { label: '发布时间', model: 'time', type: 'daterange' },
  { label: '是否公开', model: 'is_use', type: 'radio' },
  { label: '简介', model: 'brief', type: 'textarea' }
])
const rules = reactive({ name: [{ required: true, message: '请输入供给名称', trigger: 'blur' }] })
// 请求
onMounted(async () => {
  loading.value = true
  await searchOther()
  await search()
  loading.value = false
})
const search = async (query = { skip, limit }) => {
  skip = query.skip
  limit = query.limit
  const info = {
    skip: query.skip,
    limit: query.limit,
    user: user.value.id,
    ...searchForm.value
  }
  const res = await store.query(info)
  if (res.errcode == '0') {
    list.value = res.data
    total.value = res.total
  }
}
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: 'method', is_use: '0' })
  if ($checkRes(result)) methodList.value = result.data
  // 需求紧急度
  result = await dictDataStore.query({ code: 'urgent', is_use: '0' })
  if ($checkRes(result)) urgentList.value = result.data
  // 技术领域
  result = await dictDataStore.query({ code: 'field', is_use: '0' })
  if ($checkRes(result)) fieldList.value = result.data
  // 需求状态
  result = await dictDataStore.query({ code: 'supplyStatus', is_use: '0' })
  if ($checkRes(result)) supplyList.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
}
// 字典数据转换
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 toAdd = () => {
  dialog.value = { type: '1', show: true, title: '发布供给' }
}
// 修改
const toEdit = (data) => {
  data.time = [data.start_time, data.end_time]
  form.value = data
  dialog.value = { type: '1', show: true, title: '修改供给' }
}
// 删除
const toDelete = (data) => {
  ElMessageBox.confirm(`您确认删除${data.name}该数据?`, '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
    .then(async () => {
      const res = await store.del(data.id)
      if ($checkRes(res, true)) {
        search({ skip, limit })
      }
    })
    .catch(() => {})
}
const toSave = async () => {
  const data = cloneDeep(form.value)
  const other = { status: '0', user: user.value.id }
  if (data.time && data.time.length > 1) {
    data.start_time = data.time[0]
    data.end_time = data.time[1]
  }
  delete data.time
  let res
  if (get(data, 'id')) res = await store.update({ ...data, ...other })
  else res = await store.create({ ...data, ...other })
  if ($checkRes(res, true)) {
    await search({ skip, limit })
    await toClose()
    await searchDemand()
    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 }
  if (data.time && data.time.length > 1) {
    data.start_time = data.time[0]
    data.end_time = data.time[1]
  }
  delete data.time
  let res
  if (get(data, 'id')) res = await store.update({ ...data, ...other })
  else res = await store.create({ ...data, ...other })
  if ($checkRes(res, true)) {
    await search({ skip, limit })
    await toClose()
    await searchDemand()
    width.value = '90%'
    dialog.value = { type: '2', show: true, title: '相关需求推荐' }
  }
}
// 审核保存
const toExam = async (row) => {
  ElMessageBox.confirm(`您确认保存并提交审核该数据?`, '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
    .then(async () => {
      const data = cloneDeep(row)
      let res = await store.update({ id: data.id, status: '0', user: user.value.id })
      if ($checkRes(res, true)) {
        await search({ skip, limit })
        await toClose()
        await searchDemand()
        width.value = '90%'
        dialog.value = { type: '2', show: true, title: '相关需求推荐' }
      }
    })
    .catch(() => {})
}
// 需求列表查询
const searchDemand = async () => {
  const info = { skip: 0, limit: 5, is_use: '0', status: '1' }
  const res = await demandStore.query(info)
  if (res.errcode == '0') demandList.value = res.data
}
// 查看详情
const toView = (item) => {
  router.push({ path: '/demand/detail', query: { id: item.id || item._id } })
}
// 地区
const getArea = (data) => {
  if (data) return data.join('-')
  else return '暂无地区'
}
const toClose = () => {
  form.value = { time: [] }
  width.value = '50%'
  dialog.value = { show: false }
}
// 分页
const changePage = (page = currentPage.value) => {
  search({ skip: (page - 1) * limit, limit: limit })
}
const sizeChange = (limits) => {
  limit = limits
  currentPage.value = 1
  search({ skip: 0, limit: limit })
}
</script>
<style scoped lang="scss">
.main {
  .one {
    height: 50px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 0 0 10px 0;
    .one_left {
      background: #1875df;
      padding: 0 10px;
      height: 30px;
      color: #fff;
      line-height: 30px;
      text-align: center;
      font-size: 16px;
      cursor: default;
    }
  }
  .thr {
    display: flex;
    justify-content: center;
    margin: 20px 0 0 0;
  }
}
.dialog {
  display: flex;
  flex-wrap: wrap;
  margin-top: 20px;
  .list {
    position: relative;
    margin-right: 10px;
    margin-bottom: 10px;
    width: 380px;
    height: 233px;
    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 {
      height: 162px;
      padding: 10px 20px 0 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;
    }
  }
}
</style>
