<template>
  <div class="bid-content-page">
    <div class="bid-container">

      <el-dialog v-model="dialogFormVisible" draggable title="提示信息" width="500" @close="close">
        <el-form label-width="auto" :model="addForm" :rules="rules" ref="formRef" style="max-height: 500px;overflow: auto;">
          <el-form-item label="登记类型">
            <el-select v-model="addForm.type" placeholder="请选择登记类型"  value-key="value" @change="handleTypeChange" >
              <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="项目名称" v-if="addForm.type == '监控中'">
            <el-select v-model="addForm.title" placeholder="请选择项目名称" @change="handleProjectChange"  value-key="id">
              <el-option v-for="item in jkList" :key="item.id" :label="item.title" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="项目名称" v-else-if="addForm.type == '投续标'">
            <el-select v-model="addForm.title" placeholder="请选择项目名称" @change="handleProjectChange"  value-key="id">
              <el-option v-for="item in txbList" :key="item.id" :label="item.title" :value="item" />
            </el-select>
          </el-form-item>
           <el-form-item label="类似项目名称" prop="title"  v-else>
              <el-cascader v-model="adminCascader" :options="adminArea" :show-all-levels="true"  @change="handleAdminCascaderChange" style="width: 100%"></el-cascader>
            </el-form-item>
          <!-- <el-form-item label="项目名称" v-else>
            <el-input v-model="addForm.title" autocomplete="off" placeholder="请输入项目名称"/>
          </el-form-item> -->
          <!-- <el-form-item label="中标类型选项">
            <el-switch v-model="finishBidObjectTemp.flag" inline-prompt active-text="从中标结果中选择" inactive-text="手动输入" style="background-color: unset;" @change="handleSwitchChange"/>
          </el-form-item>
          <div v-if="finishBidObjectTemp.flag">
            <el-form-item label="中标项目">
              <el-select v-model="finishBidObject" filterable placeholder="请选择中标项目" style="width: 100%;overflow: auto;"  @change="handleChange" value-key="id">
                <el-option v-for="item in finishBidOption" :key="item.id" :label="item.title" :value="item" :title="item.title" style="width: 380px;"/>
              </el-select>
            </el-form-item>
          </div>
          <div v-else> -->
            <div v-if="addForm.type == '新创建'">
              <el-form-item label="是否续标">
                <el-switch v-model="addForm.c_is_xb" inline-prompt active-text="是" inactive-text="否" style="background-color: unset;" @change="handleXBSwitchChange"/>
              </el-form-item>
            </div>
            <el-form-item label="中标结果URL">
              <el-input v-model="finishBidObjectTemp.url" placeholder="请输入中标结果URL"/>
            </el-form-item>
          <!-- </div> -->
          <div  v-if="addForm.type != '监控中'">
              <el-form-item label="管理区域" prop="c_glqy">
                <el-cascader ref="areaCascader" v-model="addFormArea" :options="allArea" :show-all-levels="true"  @change="handleNodeAreaClick" style="width: 100%"></el-cascader>
              </el-form-item>
              <el-form-item label="投标日期" prop="tb_date">
                <el-date-picker
                  style="width: 100%;"
                  v-model="addForm.tb_date"
                  type="date"
                  placeholder="请选择投标日期"
                />
              </el-form-item>
              <el-form-item label="投标报价" prop="tb_money">
                <el-input-number
                  style="width: 100%"
                  v-model="addForm.tb_money"
                  controls-position="right"
                  placeholder="请输入投标报价"
                />
              </el-form-item>
              <el-form-item label="招标编号" prop="zb_code">
                <el-input v-model="addForm.zb_code" autocomplete="off" placeholder="请输入招标编号"/>
              </el-form-item>
              <el-form-item label="招标项目名称" prop="zb_name">
                <el-input v-model="addForm.zb_name" autocomplete="off" placeholder="请输入招标项目名称"/>
              </el-form-item>
              <el-form-item label="招标发布机构" prop="zb_org">
                <el-input v-model="addForm.zb_org" autocomplete="off" placeholder="请输入招标发布机构"/>
              </el-form-item>
              <el-form-item label="招标数据来源" prop="zb_source">
                <el-input v-model="addForm.zb_source" autocomplete="off" placeholder="请输入招标数据来源"/>
              </el-form-item>
              <el-form-item label="招标金额" prop="zb_money">
                <el-input-number
                  style="width: 100%"
                  v-model="addForm.zb_money"
                  controls-position="right"
                  placeholder="请输入招标金额"
                />
              </el-form-item>
              <el-form-item label="开标发布日期" prop="zb_startdate">
                <el-date-picker
                  style="width: 100%;"
                  v-model="addForm.zb_startdate"
                  type="datetime"
                  placeholder="请选择开标发布日期"
                />
              </el-form-item>
              <el-form-item label="开标截止日期" prop="zb_enddate">
                <el-date-picker
                  style="width: 100%;"
                  v-model="addForm.zb_enddate"
                  type="datetime"
                  placeholder="请选择开标截止日期"
                />
              </el-form-item>
              <el-form-item label="招标详情URL" prop="zb_url">
                <el-input v-model="addForm.zb_url" autocomplete="off" placeholder="请输入招标详情URL"/>
              </el-form-item>
                
          </div>

          <div  v-if="addForm.type != '监控中'">
              <el-form-item label="业态" prop="c_ytfw">
                <el-tree-select
                      placeholder="请选择业态"
                      v-model="addFormYT"
                      :data="ytList"
                      collapse-tags
                      filterable
                      style="width: 100%"
                    />
              </el-form-item>
              <el-form-item label="委托类型" prop="c_zgfw">
                <el-radio v-model="addFormZgfw" label="全委">全委</el-radio>
                <el-radio v-model="addFormZgfw" label="单一单委">单一单委</el-radio>
                <el-radio v-model="addFormZgfw" label="多项单委">多项单委</el-radio>
              </el-form-item>
              
              <el-form-item label="服务类型" prop="c_fwlx">
                <el-checkbox-group v-model="addFormFwlx">
                  <el-checkbox label="会务"></el-checkbox>
                  <el-checkbox label="工程"></el-checkbox>
                  <el-checkbox label="绿化"></el-checkbox>
                  <el-checkbox label="保安"></el-checkbox>
                  <el-checkbox label="保洁"></el-checkbox>
                </el-checkbox-group>
              </el-form-item>

          </div>


        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="close" class="btn">取消</el-button>
            <el-button type="primary" class="btn enter-btn" @click="submitForm(formRef)">
              确认
            </el-button>
          </div>
        </template>
      </el-dialog>

    </div>
  </div>
</template>

<script setup lang="ts">
import { ref,onMounted } from 'vue'
import moment from 'moment'
import api from '@/api/common'
import CONFIG from '@/utils/config'
import type { FormInstance } from 'element-plus'
const formRef = ref<FormInstance>()

const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
const userName = userInfo?.username =='user_xtw' ? '徐天炜' : userInfo?.username || ''

const props = defineProps({
  flag: {
    type: Boolean,
    default: false,
  },
  close: {
    type: Function,
    default: () => {},
  }
})


interface resultForm {
  [key: string]: any
}
const finishObject = ref<resultForm>({})
const finishProjects = ref<any[]>([])
const finishTreeProjects = ref<any[]>([])

const txbList = ref<any[]>([])
const jkList = ref<any[]>([])

const ytList = ref<resultForm[]>([])
const glArea = ref([{} as TreeItem])
const addFormZgfw = ref('')
const addFormFwlx = ref([])
const addFormYT = ref('')
const addFormArea = ref([])

interface TreeItem {
  id: string | number
  value: string
  label: string
  children: TreeItem[],
  [key: string]: any
}
const areaCascader = ref(null)
const areaObject = ref({})
const adminCascader = ref([])
const adminArea = ref([{} as TreeItem])
const allArea = ref([{} as TreeItem])
const finishBidOption = ref([{} as resultForm])
const jkBidObject = ref<any>(null)
const txbBidObject = ref<any>(null)
const finishBidObject = ref<any>(null)
const finishBidObjectTemp = ref({
  flag:false,
  url:''
})

onMounted(() => {
  initData()
})
const initData = async () => {
    await getFinishProjects()
    const itemTxbList = await getTypeProjects(CONFIG.COLUMNIDARR[2]) // 投续标项目
    const itemJkList = await getTypeProjects(CONFIG.COLUMNIDARR[6]) // 中标监控项目
    const itemFinishList = await getTypeProjects(CONFIG.COLUMNIDARR[7]) // 已中标项目
    const itemYtList = await getTypeProjects(CONFIG.COLUMNIDARR[8]) // 业态
    const itemGLList = await getTypeProjects(CONFIG.COLUMNIDARR[9]) // 管理区域
    console.log(itemFinishList)
    finishBidOption.value = itemFinishList.data || []
    txbList.value = []
    jkList.value = []
    glArea.value = []
    allArea.value = []
    ytList.value = []
    itemTxbList.data.filter((item: any) => {
        const json = JSON.parse(item.c_xmjd_json)
        if(json.length > 0 &&  json[json.length - 1].xmjd < 6){
        txbList.value.push(item)
        }
    })
    itemJkList.data.filter((item: any) => {
        const flag = item.c_sfzb
        if(flag == false){// 已中标
            jkList.value.push(item)
        }
    })
    ytList.value = itemYtList.data.map((item: any) => ({
        ...item,
        label: item.c_yt_name,
        value: item.c_yt_name,
        children: item.children || []
    }))
    // glArea.value = itemGLList.data
    //     .filter((item: any) => item?.c_part_name && item?.c_district_code?.startsWith('3101')) // 过滤空、null、undefined、''
    //     .map((item: any) => ({
    //     label: item.c_part_name,
    //     value: item.c_part_name,
    //     children: []
    // }))
    // const uniqueGlTree = Array.from(
    //     new Map(glArea.value.map(item => [item.value, item])).values()
    // )
    // glArea.value = uniqueGlTree

    adminArea.value = itemGLList.data.filter((item: any) => item?.c_district_name && item?.c_district_code?.startsWith('310')) // 过滤空、null、undefined、''
      .map((item: any) => ({
        label: item.c_district_name,
        value: item.c_district_name,
        children: finishTreeProjects.value.filter((item2: any) => item.c_district_name.includes(item2.c_sq))
      }))
      const uniqueTree = Array.from(
        new Map(adminArea.value.map(item => [item.value, item])).values()
      )
    adminArea.value = uniqueTree
    allArea.value = buildAreaTree(itemGLList.data)
    console.log(itemFinishList)
}
const dialogFormVisible = props.flag
const close = () => {
  props.close()
}

const getFinishProjects = async () => {
  const params: any = {
    columnId: CONFIG.COLUMNIDARR[0], //原项目数据
    orderBy: JSON.stringify([{ field: "c_zgxmhtdqrq", orderByType: 1 }]),
    states: '0',// 只看草稿箱
    pageSize: 9999,
    page: 0
  }
  await api.getDmsDataList(params).then(res => {
    if ((res as any).code === 200) {
      finishProjects.value = (res as any).content.data
      finishTreeProjects.value = buildTree(finishProjects.value)
      
    }else{
      finishProjects.value = []
    }
  })
}
const buildTree = (data: any[]): any[] => {
  const map = new Map()
  const tree: any[] = []

  data.forEach((item: any) => {
    map.set(item.c_guid, {
      ...item,
      value: item.id,
      label: item.title,
      children: []
    })
  })

  data.forEach((item: any) => {
    const node = map.get(item.c_guid)
    if (item.c_father_code && map.has(item.c_father_code)) {
      // map.get(item.c_father_code).children.push(node)
    } else {
      tree.push(node)
    }
  })
  return tree
}

const typeOptions = ref([
{
    value: '新创建',
    label: '新创建',
},
{
    value: '监控中',
    label: '监控中',
},
{
    value: '投续标',
    label: '投续标',
},
])


const addForm = ref({
  id: '',
  type: '新创建',
  title: '',
  tb_date:'',
  tb_money:'',
  zb_code:'',
  zb_name:'',
  zb_org:'',
  zb_source:'',
  zb_money:'',
  zb_startdate:'',
  zb_enddate:'',
  zb_url:'',
  c_is_xb:false,
})

const rules = ref({
  
})
// interface ProjectItem {
//   [key: string]: any
// }
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      if(addForm.value.type == '监控中'){
        //流程
        const id = 7  // 固定进度数值
        const rwlcqd = JSON.parse(txbBidObject.value.rwlcqd || '[]')
        rwlcqd.find((p: any) => p.id == id).done = true
        rwlcqd.find((p: any) => p.id == id).create_time = moment().format('YYYY-MM-DD HH:mm')
        rwlcqd.find((p: any) => p.id == id).username = userName
        rwlcqd.find((p: any) => p.id == id).userid = userInfo?.id || ''
        rwlcqd.find((p: any) => p.id == id).type = 0

        // 进度
        let xmjd_json = JSON.parse(txbBidObject.value.c_xmjd_json || '[]');
        xmjd_json[5].create_time = moment().format('YYYY-MM-DD HH:mm')
        xmjd_json[5].username = userName
        xmjd_json[5].userid = userInfo?.id || ''
        xmjd_json[5].type = 0
        if(!xmjd_json[6]){
          xmjd_json.push({xmjd: id, type: 1, create_time: '', username: '', userid: ''})
        }
        const content = JSON.stringify({
          id: txbBidObject.value.id,
          rwlcqd:rwlcqd,
          c_xmjd_json:xmjd_json
        })
        updateProject(CONFIG.COLUMNIDARR[2],CONFIG.MODELIDARR[0],content)
        // 修改中标监控
        const steps = [
          { n: 1, label: '预警触发'},
          { n: 2, label: '投/续标准备'},  
          { n: 3, label: '招标监控'},
          { n: 4, label: '标书制作'},
          { n: 5, label: '投标提交'},
          { n: 6, label: '开标监控'},
          { n: 7, label: '确认中标'},
        ]
        let json = xmjd_json.map((item:any) => {
          return {
            create_time: item.create_time ? item.create_time : moment().format('YYYY-MM-DD HH:mm'),
            desc:steps.find((s:any) => s.n == item.xmjd)?.label || '',
            username:item.username ? item.username : userName,
            userid:item.userid ? item.userid : userInfo?.id || '',
          }
        })
        const content2 = JSON.stringify({
          id: jkBidObject.value.id || '',
          c_gljg: finishBidObjectTemp.value?.flag ? finishBidObject.value?.id : '',
          c_jgjk_url: finishBidObjectTemp.value?.flag ? finishBidObject.value?.c_detail_url : finishBidObjectTemp.value?.url || '',
          c_lcsjx:json || '',
          c_sfzb:true,
          c_type:"中标登记",
          c_enable: false
        })
        updateProject(CONFIG.COLUMNIDARR[6],CONFIG.MODELIDARR[3],content2)

      }else if(addForm.value.type == '投续标'){
        //流程
        const rwlcqd = JSON.parse(selectedObject.value.rwlcqd || '[]')
        rwlcqd.forEach((p: any) => {
          if(!p.danger && p.id !=8){//未处理的流程全部重新处理
            p.done = true,
            p.create_time = moment().format('YYYY-MM-DD HH:mm'),
            p.username = userName,
            p.userid = userInfo?.id || '',
            p.type = 0
          }
        })
        let xmjd_json = JSON.parse(selectedObject.value.c_xmjd_json || '[]');
        const curNumber = xmjd_json[xmjd_json.length - 1].xmjd
        for(let i = curNumber; i < 8; i++){
           if(i == curNumber){
            xmjd_json[i-1].create_time = moment().format('YYYY-MM-DD HH:mm')
            xmjd_json[i-1].username = userName
            xmjd_json[i-1].userid = userInfo?.id || ''
            xmjd_json[i-1].type = 0
           }else{
              if( i == 7){
                xmjd_json.push({xmjd: i, type: 1, create_time: '', username: '', userid: ''})
              }else{
                xmjd_json.push({xmjd: i, type: 0, create_time: moment().format('YYYY-MM-DD HH:mm'), username: userName, userid: userInfo?.id || ''}) 
              }
           }
        }
        const steps = [
          { n: 1, label: '预警触发'},
          { n: 2, label: '投/续标准备'},  
          { n: 3, label: '招标监控'},
          { n: 4, label: '标书制作'},
          { n: 5, label: '投标提交'},
          { n: 6, label: '开标监控'},
          { n: 7, label: '确认中标'},
        ]
        let json = xmjd_json.map((item:any) => {
          return {
            create_time: item.create_time ? item.create_time : moment().format('YYYY-MM-DD HH:mm'),
            desc:steps.find((s:any) => s.n == item.xmjd)?.label || '',
            username:item.username ? item.username : userName,
            userid:item.userid ? item.userid : userInfo?.id || '',
          }
        })


        // 开标监控
        let kbFormData = {
          title: selectedObject.value.title,
          content: selectedObject.value.content,
          c_zbbh: selectedObject.value.c_xgzb ? selectedObject.value.c_xgzb : addForm.value.zb_code,
          c_sfzb: true,
          c_jgjk_url: finishBidObjectTemp.value?.url || '',
          c_kbsj: selectedObject.value.zbjzsj ? selectedObject.value.zbjzsj : addForm.value.zb_enddate,
          c_xmmc: selectedObject.value.c_xmbt,
          c_zbtjr: selectedObject.value.tbrq ? selectedObject.value.tbrq : addForm.value.tb_date,
          c_tbbj: selectedObject.value.tbbj ? selectedObject.value.tbbj : addForm.value.tb_money,
          c_glxm: selectedObject.value.xmbh,
          c_lcsjx: json || '',
          c_type: '中标登记',
          c_enable: false
        }
        console.log(kbFormData)
        const res = await addContentParams(kbFormData,CONFIG.COLUMNIDARR[6],CONFIG.MODELIDARR[3])
        let desc = {
          zb_project_code: selectedObject.value.c_xgzb ? selectedObject.value.c_xgzb : addForm.value.zb_code,
          zb_source_name: addForm.value.zb_source,
          zb_project_name: addForm.value.zb_name,
          zb_budget_amount: selectedObject.value.tbbj ? selectedObject.value.tbbj : addForm.value.tb_money,
          zb_detail_url: finishBidObjectTemp.value?.url || '',
          zb_publish_time:  selectedObject.value.zbkssj ? selectedObject.value.zbkssj : addForm.value.zb_startdate,
          zb_bid_deadline: selectedObject.value.zbjzsj ? selectedObject.value.zbjzsj : addForm.value.zb_enddate,
          zb_author: userName
        }
        let areaArr = (areaObject.value as any)?.pathLabels || []
        let tbFormData = {
          id: selectedObject.value.id || '',
          c_zgfw: selectedObject.value.c_zgfw ? selectedObject.value.c_zgfw : addFormZgfw.value,
          c_xgzb: selectedObject.value.c_xgzb ? selectedObject.value.c_xgzb : addForm.value.zb_code,
          c_xgjk: (res as any).content || '',
          c_xmbtqc: selectedObject.value.c_xmbt,
          c_qx: selectedObject.value.c_qx ? selectedObject.value.c_qx : areaArr[0] || '',
          c_xmbt: selectedObject.value.c_xmbt,
          c_xmjd_json:xmjd_json,
          zbxmbh: selectedObject.value.c_xgzb ? selectedObject.value.c_xgzb : addForm.value.zb_code,
          tbrq: selectedObject.value.tbrq ? selectedObject.value.tbrq : addForm.value.tb_date,
          tbbj: selectedObject.value.tbbj ? selectedObject.value.tbbj : addForm.value.tb_money,
          zbkssj: selectedObject.value.zbkssj ? selectedObject.value.zbkssj : addForm.value.zb_startdate,
          zbjzsj: selectedObject.value.zbjzsj ? selectedObject.value.zbjzsj : addForm.value.zb_enddate,
          rwlcqd: rwlcqd,
          zbmsxx: selectedObject.value.zbmsx ? selectedObject.value.zbmsx : desc,
          c_ytfw: selectedObject.value.ytfxw ? selectedObject.value.ytfxw : addFormYT.value,
          c_fwlx: selectedObject.value.fwlx ? selectedObject.value.fwlx : addFormFwlx.value.toString(),
          c_glqy: selectedObject.value.glqy ? selectedObject.value.glqy : areaArr[1] || '',
        }
        updateProject(CONFIG.COLUMNIDARR[2],CONFIG.MODELIDARR[0],JSON.stringify(tbFormData))
        // console.log("其他")
      }else{
        console.log("其他")
         //流程
        const rwlcqd = CONFIG.TASKLIST
        rwlcqd.forEach((p: any) => {
          if(!p.danger && p.id !=8){//未处理的流程全部重新处理
            p.done = true,
            p.create_time = moment().format('YYYY-MM-DD HH:mm'),
            p.username = userName,
            p.userid = userInfo?.id || '',
            p.type = 0
          }
        })
        let xmjd_json = [];
        for(let i = 1; i < 8; i++){
            if( i == 7){
              xmjd_json.push({xmjd: i, type: 1, create_time: '', username: '', userid: ''})
            }else{
              xmjd_json.push({xmjd: i, type: 0, create_time: moment().format('YYYY-MM-DD HH:mm'), username: userName, userid: userInfo?.id || ''}) 
            }
        }
        const steps = [
          { n: 1, label: '预警触发'},
          { n: 2, label: '投/续标准备'},  
          { n: 3, label: '招标监控'},
          { n: 4, label: '标书制作'},
          { n: 5, label: '投标提交'},
          { n: 6, label: '开标监控'},
          { n: 7, label: '确认中标'},
        ]
        let json = xmjd_json.map((item:any) => {
          return {
            create_time: item.create_time ? item.create_time : moment().format('YYYY-MM-DD HH:mm'),
            desc:steps.find((s:any) => s.n == item.xmjd)?.label || '',
            username:item.username ? item.username : userName,
            userid:item.userid ? item.userid : userInfo?.id || '',
          }
        })
        // 开标监控
        let kbFormData = {
          title: finishObject.value.title,
          content: finishObject.value.content,
          c_zbbh: addForm.value.zb_code,
          c_sfzb: true,
          c_jgjk_url: finishBidObjectTemp.value?.url || '',
          c_kbsj: addForm.value.zb_enddate,
          c_xmmc: finishObject.value.c_xmmc,
          c_zbtjr: addForm.value.tb_date,
          c_tbbj: addForm.value.tb_money,
          c_glxm: finishObject.value.c_guid,
          c_lcsjx: json || '',
          c_type: '中标登记',
          c_enable: false
        }
        console.log(kbFormData)
        const res = await addContentParams(kbFormData,CONFIG.COLUMNIDARR[6],CONFIG.MODELIDARR[3])
        let desc = {
          zb_project_code: addForm.value.zb_code,
          zb_source_name: addForm.value.zb_source,
          zb_project_name: addForm.value.zb_name,
          zb_budget_amount: addForm.value.tb_money,
          zb_detail_url: finishBidObjectTemp.value?.url || '',
          zb_publish_time:  addForm.value.zb_startdate,
          zb_bid_deadline: addForm.value.zb_enddate,
          zb_author: userName
        }
        let areaArr = (areaObject.value as any)?.pathLabels || []
        let tbFormData = {
          title: finishObject.value.title,
          content: finishObject.value.content,
          c_sfzb: finishObject.value.c_htqyjf,
          c_zgfw: addFormZgfw.value ? addFormZgfw.value : finishObject.value.c_wtfs || '',
          c_kssj: moment(finishObject.value.c_zgxmhtksrq).format('YYYY-MM-DD HH:mm') || '',
          c_dqsj: moment(finishObject.value.c_zgxmhtdqrq).format('YYYY-MM-DD HH:mm') || '',
          xmbh: finishObject.value.c_guid,
          c_nh: finishObject.value.c_nhhtsr || '',
          c_is_xb: addForm.value.c_is_xb,
          c_xgzb: addForm.value.zb_code,
          c_xgjk: (res as any).content || '',
          c_xmbtqc: finishObject.value.c_xmmc,
          c_qx: areaArr[0] ? areaArr[0] : finishObject.value.c_sq || '',
          c_xmbt: finishObject.value.c_xmmc,
          c_xmjd_json:xmjd_json,
          zbxmbh: addForm.value.zb_code,
          tbrq: addForm.value.tb_date,
          tbbj: addForm.value.tb_money,
          zbkssj: addForm.value.zb_startdate,
          zbjzsj: addForm.value.zb_enddate,
          rwlcqd: rwlcqd,
          zbmsxx: desc,
          c_ytfw: addFormYT.value,
          c_fwlx: addFormFwlx.value.toString(),
          c_glqy: areaArr[1] ? areaArr[1] : finishObject.value.c_glqynbkj || '',
        }
        await addContentParams(tbFormData,CONFIG.COLUMNIDARR[2],CONFIG.MODELIDARR[0])
      }
    } else {
      // console.log('error submit!')
    }
  
    close()
  })
}
const addContentParams = async (formData: any,columnId:number,modelId:number) => {
    const params = {
        content: JSON.stringify(formData),
        columnId: columnId,
        modelId: modelId,
      }
      const res = await api.addContent(params)
      return res
}

const handleTypeChange = (val: any) => {
  addForm.value.title = ''
  addForm.value.type = val || ''
}
const selectedObject = ref<any>({})
const handleProjectChange = async (val: any) => {
  addForm.value.title = val.title || ''
  jkBidObject.value = null
  txbBidObject.value = null
  finishBidObject.value = null
  if(addForm.value.type == '监控中'){
    jkBidObject.value = val
    const res = await getTxbBidContent(CONFIG.COLUMNIDARR[2],val.id,"c_xgjk")
    txbBidObject.value = res || {}
  }else{
    selectedObject.value = val
  }
  console.log("项目名称:", val)
}
const getTypeProjects = async (columnId:number) => {
  const params: any = {
    columnId: columnId,
    orderBy: JSON.stringify([{ field: "update_time", orderByType: 2 }]),
    states: '0,1,2,3,4',
    pageSize: 9999,
    page: 0
  }
  const res = await getDmsDataList(params)
  return (res as any).content
}


const getDmsDataList = async (params: any) => {
  return await api.getDmsDataList(params)
}

const updateProject = async (columnId:number,modelId:number,content:string) => {
  const params: any = {
    columnId: columnId,
    modelId: modelId,
    content: content,
  }
  // console.log(params)
  const res = await api.updateContent(params)
  if ((res as any).code === 200) {
    // ElMessage.success('添加成功')
    initData()
  }else{
    // ElMessage.error('添加失败')
  }
}

// const handleSwitchChange = (val: any) => {
//   finishBidObjectTemp.value.flag = val
//   finishBidObjectTemp.value.url = ''
//   finishObject.value = {}
// }
// const handleChange = (val: any) => {
//   finishBidObject.value = val
// }

const handleXBSwitchChange = (val: any) => {
  addForm.value.c_is_xb = val
  console.log(val)
}
// 获取投续标内容
const getTxbBidContent = async (columnId:number,search:string,type:string) => {
  const params: any = {
      columnId: columnId,
      orderBy: JSON.stringify([{ field: "update_time", orderByType: 2 }]),
      states: '0,1,2,3,4',
      pageSize: 1,
      page: 0
  }
  if (search) {
    params.search = JSON.stringify([
        ...(params.search ? JSON.parse(params.search) : []),
        {
          field: type,
          searchType: 1,
          content: { value: search },
        },
    ]);
  }
  const res = await getDmsDataList(params)
  return (res as any).content.data[0]
}
const buildAreaTree = (flatList: any[]) => {
  const districtMap = new Map<string, TreeItem>()
  const filteredList = flatList.filter(item => item?.c_district_code?.startsWith('3101'))
  for (const item of filteredList) {
    const districtCode = item.c_district_code
    const districtName = item.c_district_name
    if (!districtCode || !districtName) continue
    let districtNode = districtMap.get(districtCode)
    if (!districtNode) {
      districtNode = {
        id: districtCode,
        label: districtName,
        value: districtCode,
        children: [],
        ...item
      }
      districtMap.set(districtCode, districtNode as TreeItem)
    }
   const partCode = item.c_part_code
    const partName = item.c_part_name
    if (!partCode || !partName) continue
    const partMap = new Map<string, TreeItem>()
    for (const child of (districtNode?.children || []) as TreeItem[]) {
      partMap.set(child.value, child)
    }
    let partNode = partMap.get(partCode)
    if (!partNode) {
      partNode = {
        id: partCode,
        label: partName,
        value: partCode,
        children: [],
        ...item
      }
      districtNode?.children?.push(partNode as TreeItem)
    }
  }
  return Array.from(districtMap.values())
}

const handleNodeAreaClick = (value: any[])  => {
  console.log('选中的值数组:', value)
  const nodes = (areaCascader.value as any)?.getCheckedNodes?.() || []
  if(nodes.length) {
    const targetNode = nodes[nodes.length - 1]
    areaObject.value = targetNode
  }
  
}

const handleAdminCascaderChange = (val: any) => {
  const tempObj = finishTreeProjects.value.filter((item: any) => item.id.includes(val[1]))[0]
  finishObject.value = tempObj
  console.log(tempObj)
}
</script>

<style scoped>
.bid-content-page {
  width: 100%;
}
.bid-container{
  height: calc(100vh - 180px);
  overflow-y: auto;
}

</style>
