<template>
  <div class="oa-sys-list-view">
    <div class="searchBox">
      <div class="form">
        <span class="formSpan">项目名称：</span>
        <el-input v-model="queryParams.xmmc" placeholder="请输入项目名称" style="width: 210px" />
      </div>
      <div class="form">
        <span class="formSpan">项目部门：</span>
        <DeptTree v-model="queryParams['xmbmId']" placeholder="请选择部门" />
      </div>
      <div class="form">
        <span class="formSpan">跟踪人员：</span>
        <UserOrgTree v-model="queryParams['gzryId']" placeholder="请选择跟踪人员" />
      </div>
      <div class="from">
        <div class="btnBox">
          <el-button type="primary" style="background: #3485ff" @click="searchHandle">
            <img src="@/assets/imgs/OA/search.png" class="mr-8px" alt="" />
            查询</el-button
          >
          <el-button type="primary" @click="addOrEditHandle()">
            <img src="@/assets/imgs/OA/open.png" class="mr-8px" alt="" />
            新增</el-button
          >
        </div>
      </div>
    </div>
    <div class="infoBox">
      <ul>
        <li v-for="(item, index) in infoList" :key="index" class="mr-40px">
          <img class="mr-8px" :src="getAssetURL(item.icon)" alt="" />
          <p>{{ item.name }}：</p>
          <h4 class="font-size-18px" v-money:unit="item.num"></h4>
        </li>
      </ul>
    </div>
    <div class="tableBox">
      <div class="table" ref="tableRef">
        <el-table
          stripe
          :data="tableData"
          style="width: 100%; height: 100%"
          :style="{ height: tableHeight + 'px' }"
          :header-cell-style="{
            background: '#E5F0FB',
            color: '#233755',
            height: '50px'
          }"
        >
          <el-table-column label="序号" width="80">
            <template #default="scope">{{ scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column
            :show-overflow-tooltip="true"
            prop="xmmc"
            label="项目名称"
            :min-width="220"
          />
          <el-table-column prop="gzry" label="跟踪人员" width="140" />
          <el-table-column
            prop="ygje"
            label="预估金额（万元）"
            :show-overflow-tooltip="true"
            width="200"
          />
          <el-table-column prop="jf" label="甲方" width="120" />
          <el-table-column prop="jfdjr" label="甲方对接人" width="120" />
          <el-table-column prop="xmbm" label="项目归属部门" width="120" />
          <el-table-column prop="xzqmc" label="行政区" width="120" />
          <el-table-column prop="zt" label="状态" width="120">
            <template #default="scope">
              {{ ztMap[scope.row.zt] }}
            </template>
          </el-table-column>
          <el-table-column prop="latestModifyTime" label="更新时间" width="120">
            <template #default="scope">
              {{ formatDate(scope.row.latestModifyTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="xmjl" label="开关" width="120">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="0"
                @change="switchChange(scope.row)"
                :inactive-value="1"
              />
            </template>
          </el-table-column>

          <el-table-column label="操作" width="80" fixed="right">
            <template #default="scope">
              <div
                class="operateBtn"
                @click="addOrEditHandle(scope.row)"
                v-if="scope.row.gzryId === user.user.id"
              >
                <span>编辑</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pageBox">
        <el-pagination
          v-model:current-page="queryParams.pageNo"
          :page-size="queryParams.pageSize"
          background
          layout="total, prev, pager, next, jumper"
          :total="total"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="660px" align-center>
      <el-form
        ref="ruleFormRef"
        style="width: 600px"
        label-width="auto"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="formData.xmmc" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="跟踪人员" prop="region">
              <UserOrgTree
                v-model="formData.gzryId"
                placeholder="请选择跟踪人员"
                @node-click="(item) => treeNodeClick(item, 'gzry')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="甲方" prop="name">
              <el-input v-model="formData.jf" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预估金额（万元）" prop="name">
              <el-input v-model="formData.ygje" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="甲方对接人" prop="name">
              <el-input v-model="formData.jfdjr" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目归属部门" prop="region">
              <DeptTree
                v-model="formData.xmbmId"
                @node-click="(item) => treeNodeClick(item, 'xmbm')"
                placeholder="请选择部门"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="行政区" prop="region">
              <DistrictTree
                class="form-item-disable-style"
                v-model="formData.xzqdm"
                @node-click="(item, labels) => treeNodeClick(labels, 'xzqmc')"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="region">
              <el-select v-model="formData.zt" placeholder="请选择状态" style="width: 100%">
                <el-option label="谋划" value="0" />
                <el-option label="待上会" value="1" />
                <el-option label="待招标" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="谁可见" prop="region">
              <UserOrgTree v-model="visibleUserIds" :multiple="true" placeholder="请选择跟谁可见" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="desc">
          <el-input v-model="formData.bz" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="saveProjectTracking"> 保存 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { DICT_TYPE, getDictLabel } from '@/utils/dict'
import { IFormType, useMixins, infoList, user } from './common'
import request from '@/config/axios'
import { formatDate } from '@/utils/formatTime'
import { getAssetURL } from '@/utils/auth'
import UserOrgTree from '@/views/OaSystem/components/UserOrgTree/index.vue'
import DeptTree from '@/views/OaSystem/components/DeptTree/index.vue'
import DistrictTree from '@/views/OaSystem/components/DistrictTree/index.vue'

defineOptions({ name: 'ProjectTrack' })

const ztMap = {
  '0': '谋划',
  '1': '待上会',
  '2': '待招标'
}
const visibleUserIds = ref<string[]>([])
const tableRef: any = ref(null)
const tableHeight: any = ref(0)
const { queryParams, formData, initFormData } = useMixins()

const handleCurrentChange = (pageNo: number) => {
  queryParams.pageNo = pageNo
  queryProjectTrackByPage()
}
/**
 * 项目跟踪：新增、编辑
 */
const dialogTitle = ref<string>('项目跟踪填报')
const dialogVisible = ref<boolean>(false)
const addOrEditHandle = (row?: IFormType) => {
  dialogVisible.value = true
  if (!row) {
    dialogTitle.value = '项目跟踪填报'
    initFormData()
    visibleUserIds.value = []
  } else {
    dialogTitle.value = '项目跟踪编辑'
    queryProjectTrackByDetail(row['id']).then((result) => {
      initFormData(result as any)
      visibleUserIds.value = result['visibleUserIds'].split(',')
    })
  }
}
const treeNodeClick = (item, type: string) => {
  if (!item) return
  if (type === 'xzqmc') {
    formData.value[type] = item.join('-')
    return
  }
  formData.value[type] = item['label'] || item['name']
}
const saveProjectTracking = async (): Promise<void> => {
  const urlApi = `/projectTracking/save`
  const sendData = {
    ...formData.value
  }
  sendData['visibleUserIds'] = visibleUserIds.value.join(',')
  const result = await request.post({ url: urlApi, data: sendData }, '/business')
  if (result) {
    searchHandle()
    dialogVisible.value = false
  }
}
const switchChange = (item) => {
  updateStatus({
    id: item['id'],
    status: item['status']
  })
}
const updateStatus = async (data: { id: string; status: string }): Promise<void> => {
  const urlApi = `/update-status`
  return await request.put({ url: urlApi, data: data }, '/business')
}
const tableData = ref<Array<any>>([])
const total = ref<number>()
const searchHandle: () => void = () => {
  queryParams.pageNo = 1
  queryProjectTrackingSummary()
  queryProjectTrackByPage()
}
const queryProjectTrackByPage = async (): Promise<void> => {
  const urlApi = `/projectTracking/page`
  const sendData = {
    ...queryParams
  }
  const result = await request.get({ url: urlApi, params: sendData }, '/business')
  tableData.value = result['list']
  total.value = result['total']
}
const queryProjectTrackByDetail = async (id: string): Promise<void> => {
  const urlApi = `/projectTracking/getById`
  const sendData = {
    id
  }
  return await request.get({ url: urlApi, params: sendData }, '/business')
}
queryProjectTrackByPage()

/**
 * 项目金额、项目个数汇总
 */
const queryProjectTrackingSummary = async (): Promise<void> => {
  const urlApi = `/projectTracking/summary`
  const sendData = {
    ...queryParams
  }
  const result = await request.get({ url: urlApi, params: sendData }, '/business')
  infoList[0]['num'] = result ? result.amount ?? 0 : 0
  infoList[1]['num'] = result ? result.nums ?? 0 : 0
}
queryProjectTrackingSummary()
onMounted(() => {
  tableHeight.value = tableRef.value.clientHeight
})
</script>

<style lang="scss" scoped>
:deep(.el-radio) {
  margin-right: 10px;
}
</style>
