<template>
    <hc-card id="add-card-target" title="项目管理">
        <template #extra>
            <!-- <el-button type="primary" class="mr-10px" @click="addRowClick">新增项目</el-button> -->
            <el-button color="#20C98B" type="primary" @click="addRowClick">
                <hc-icon class="text-white" name="add" />
                <span class="text-white">新增项目</span>
            </el-button>
            <!-- <el-button type="warning" class="mr-10px" color="orange">
                <HcIcon name="file-transfer" class="text-white" />
                <span class="text-white" @click="importClick">导入项目</span>
            </el-button> -->
            <el-button v-del-com:[batRowDelClick] type="danger" :disabled="tableCheckKeys.length <= 0">
                <HcIcon name="delete-bin" class="text-white" />
                删除项目
            </el-button>
        </template>
        <template #search>
            <div class="w-[150px]">
                <el-select v-model="searchForm.type" filterable clearable block placeholder="项目类型" @change="typeClick">
                    <el-option v-for="item in typeOptions" :key="item.id" :label="item.dictValue" :value="item.id" />
                </el-select>
            </div>
            <div class="ml-2 w-[150px]">
                <el-select v-model="searchForm.routeType" filterable clearable block placeholder="路线类型" @change="searchClick">
                    <el-option v-for="item in routeOptions" :key="item.id" :label="item.dictValue" :value="item.id" />
                </el-select>
            </div>
            <div class="ml-2 w-[150px]">
                <el-select v-model="searchForm.stage" filterable clearable block placeholder="项目阶段" @change="searchClick">
                    <el-option v-for="item in stateOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </div>
         
       
            <div class="ml-2 w-[200px]">
                <el-select v-model="searchForm.operationCompany" filterable clearable block placeholder="运营公司" @change="searchClick">
                    <el-option v-for="item in operationCompanyOptions" :key="item.operationCompany" :label="item.operationCompany" :value="item.operationCompany" />
                </el-select>
            </div>
            <div class="relative ml-3 w-[260px]">
                <hc-search-input v-model="searchForm.name" color="#151921" text="搜索" @search="searchClick" />
            </div>
            <!-- <div class="relative ml-3">
                <el-button color="gray" type="primary" @click="resetClick">
                    <span class="text-white">重置</span>
                </el-button>
            </div>
            <div class="relative ml-3 w-[260px]">
                <el-button type="primary" color="#2550A2" @click="resetClick">
                    <span class="text-white">筛选</span>
                </el-button>
            </div> -->
        </template>

        <hc-table
            :column="tableColumn" :datas="tableData" :index-style="{ width: 60 }" :loading="tableLoading"
            is-check :check-style="{ fixed: true, width: 29 }" @selection-change="tableCheckChange"
        >
            <template #stage="{ row }">
                <!-- <el-link type="primary" @click="editRowClick(row)">{{ row.key3 }}</el-link> -->
                <el-tag v-if="row.stage === 1" type="primary">{{ row.stageName }}</el-tag>
                <el-tag v-if="row.stage === 2" type="success">{{ row.stageName }}</el-tag>
            </template>
            <template #action="{ row }">
                <el-link type="warning" @click="rowViewClick(row)">查看</el-link>
                <el-link type="primary" @click="editRowClick(row)">编辑</el-link>
              
                <el-link v-del-com:[rowDelClick]="row" type="danger">删除</el-link>
            </template>
        </hc-table>
        <template #action>
            <hc-pages :pages="searchForm" @change="pageChange" />
        </template>
    </hc-card>

    <!-- 新增、编辑 -->
    <HcAddAndEdit v-model="isAddAndEditShow" :data="addAndEditForm" @close="addAndEditClose" @finish="addAndEditSubmit" />




    <!-- 导入 -->
    <hc-dialog v-model="isImportShow" widths="24rem" title="项目数据导入" :footer="false" @close="modalImportClose">
        <hc-form-upload
            v-model="importFile" class="hc-form-drop-upload"
            :options="{ num: 1, type: 'list', drop: true }"
            :upload="{ options: uploadOptions }" @success="uploadSuccess"
        />
        <div class="hc-flex mt-5">
            <span class="mr-2">模板下载:</span>
            <el-button color="#20C98B" size="small" class="text-white" :loading="downloadTemplateLoading" @click="downloadTemplate">点击下载</el-button>
        </div>
    </hc-dialog>
</template>

<script setup>
import { nextTick, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import HcAddAndEdit from './data/addAndEdit.vue'
import { getDictionaryData } from '~src/utils/tools'
import { useClick } from 'hc-vue3-ui'
import { arrToId, getArrValue, getObjValue } from 'js-fast-way'
import projectApi from '~api/promanage/project'
import { getDictionary } from '~api/dictbiz.js'



//初始组合式
const router = useRouter()
const useRoutes = useRoute()

const type = ref(useRoutes.query.type)
const operationCompany = ref(useRoutes.query.operationCompany)
//渲染完成
onMounted(async () => {
  
    await nextTick()
    searchForm.value.type = type.value
    searchForm.value.operationCompany = operationCompany.value
    await getProStation()
    await getProType()
    await getProRouteType()
    await getProOperationCompany()
    searchClick()
})

//搜索条件
const searchForm = ref({ current: 1, size: 20, total: 0, stage: null, type: null, projectName:null, routeType: null, operationCompany: null })

//项目阶段
const stateOptions = ref([])
const getProStation = async () => {
    stateOptions.value = await getDictionaryData('ibaProjectStage', true)

}
//项目类型
const typeOptions = ref([])
const getProType = async () => {
   await getTypeListData(1, 'ibaProjectType')
 }
//获取字典数
const getTypeListData = async (parentId, code) => {
        const { data } = await getDictionary({ parentId, code, type:2 })

        if (code === 'ibaProjectType') {
            typeOptions.value = getArrValue(data)
            return
        } else {
            routeOptions.value = getArrValue(data)
            return
        }
        
    
    
}
//路线类型
const routeOptions = ref([])
const getProRouteType = async () => {
    await getTypeListData(searchForm.value.type, 'ibaRouteType')
    
}
//运营公司
const operationCompanyOptions = ref([])
const getProOperationCompany = async () => {

  
    const { error, code, data } = await projectApi.selectProjectOrCompanyList({ type: 2 })
    //处理数
    if (!error && code === 200) {
        operationCompanyOptions.value = getArrValue(data)
     
    } else {
        operationCompanyOptions.value = []
  
    }
}

//搜索
const typeClick = async (val) => {
    searchForm.value.routeType = ''
    await getTypeListData(val, 'ibaRouteType')
    searchClick()
}
const resetClick = async () => {
    searchForm.value = { current: 1, size: 20, total: 0, stage: null, type: null, projectName:null, routeType: null, operationCompany: null }
    searchClick()
}
const searchClick = () => {
    searchForm.value.current = 1
    getTableData()
}

//分页
const pageChange = ({ current, size }) => {
    searchForm.value.current = current
    searchForm.value.size = size
    getTableData()
}

//表格数据
const tableColumn = [
    { key: 'typeName', name: '项目类型' },
    { key: 'routeTypeName', name: '线路类型', align: 'center' },
    { key: 'projectName', name: '路段名称', align: 'center' },
    { key: 'stage', name: '项目阶段', align: 'center' },
    { key: 'actualOperatingMileage', name: '实际运营里程（公里）', align: 'center' },
    { key: 'lane', name: '车道数', width: 80, align: 'center' },
    { key: 'operationCompany', name: '运营公司', align: 'center' },
    { key: 'action', name: '操作', width: 160, fixed:'right', align: 'center' },
]
const tableData = ref([
    
])

//获取表格数据
const tableLoading = ref(false)
const getTableData = async () => {
    tableData.value = []
  
    tableLoading.value = true
    const { error, code, data } = await projectApi.page(searchForm.value)
    //处理数据
    tableLoading.value = false
    if (!error && code === 200) {
        tableData.value = getArrValue(data['records'])
        searchForm.value.total = data.total || 0
    } else {
        tableData.value = []
        searchForm.value.total = 0
    }
}

//表格被选择
const tableCheckKeys = ref([])
const tableCheckChange = (row) => {
    tableCheckKeys.value = row
}

//新增项目
const addRowClick = async () => {
    addAndEditForm.value = {}
    await nextTick()
    isAddAndEditShow.value = true
}

//编辑项目
const editRowClick = async (row) => {
    // addAndEditForm.value = {
    //     ...row,
    //     isView: false,
    //     isEdit: true,
    // }
    await getProjectDetail(row.id)
    await nextTick()
    isAddAndEditShow.value = true
}
//获取详情
const getProjectDetail = async (id) => {
    const { error, code, data } = await projectApi.ibaProject({ id })
    if (!error && code === 200) {
        addAndEditForm.value = getObjValue(data)
    } else {
        addAndEditForm.value = {}
    }
}

//新增、编辑 显示
const isAddAndEditShow = ref(false)
const addAndEditForm = ref({})

//新增、编辑提交
const addAndEditSubmit = () => {
    getTableData()
    // addAndEditClose()
}

//新增、编辑关闭
const addAndEditClose = () => {
    isAddAndEditShow.value = false
    // addAndEditForm.value = {}
    searchForm.value.type = null
    getTableData()
    //     setTimeout(()=>{
    //     window.location.reload()
    //    }, 1000)
}



//查看数据
const isViewShow = ref(false)

const rowViewClick = async (row) => {

    await nextTick()
    await getProjectDetail(row.id)
    isAddAndEditShow.value = true
    isViewShow.value = true
    addAndEditForm.value .isView = true
    
}


//批量删除

//删除

const rowDelClick = async ({ item }, resolve) => {
    
    const { error, code, msg } = await projectApi.del(item.id)
    if (!error && code === 200) {
        window.$message.success('删除成功')
      searchClick()
        resolve()
      
    } else {
     
        resolve()
    }
}
const batRowDelClick = async (_, resolve) => {
    const ids = arrToId(tableCheckKeys.value)
    const { error, code, msg } = await projectApi.del(ids)
    if (!error && code === 200) {
        window.$message.success('删除成功')
      searchClick()
        resolve()
      
    } else {
     
        resolve()
    }
}


//导入
const isImportShow = ref(false)
const importFile = ref([])
const uploadOptions = {
    url: '/api/blade-attach/project/import-project',
    size: 120,
    accept: '.xls,.xlsx',
    accept_tip: '请选择Excel文件',
}
const importClick = () => {
    isImportShow.value = true
}
const modalImportClose = () => {
    isImportShow.value = false
}

//下载模板
const downloadTemplateLoading = ref(false)
const downloadTemplate = async () => {
    await useClick() //这里要使用 await 来等待
    downloadTemplateLoading.value = true
    // const { error, data, msg } = await mainApi.exportTemplate()
    // downloadTemplateLoading.value = false
    // if (error && isNullES(data)) {
    //     window.$message?.error(msg ?? '数据异常')
    //     return
    // }
    // await window.electron.ipcRenderer.invoke('download-file', data)
    downloadTemplateLoading.value = false
}

//上传完成
const uploadSuccess = ({ res }) => {
    modalImportClose()
    window?.$message.success(res.msg)
    getTableData()
}
</script>

<style lang="scss">
.hc-card-item-box.hc-project-data-view-info {
    background: #f9f9f9;
    border-radius: 5px;
    .select-year {
        width: 100px;
    }
}
</style>
