<template>
    <HcCard>
        <template #header>
            <div class="w-36">
                <el-select v-model="searchForm.areaId" block clearable placeholder="请选择区域" size="large">
                    <el-option v-for="item in areaType" :key="item.id" :label="item.areaName" :value="item.id" />
                </el-select>
            </div>
            <div class="w-36 ml-4">
                <el-date-picker v-model="searchForm.startDate" class="block" type="date" value-format="YYYY-MM-DD" placeholder="开始日期" clearable size="large" />
            </div>
            <div class="mx-2">
                ~
            </div>
            <div class="w-36">
                <el-date-picker v-model="searchForm.endDate" class="block" type="date" value-format="YYYY-MM-DD" placeholder="结束日期" clearable size="large" />
            </div>
            <div class="w-48 ml-2">
                <el-input v-model="searchForm.name" clearable placeholder="请输入名称进行查询" size="large" />
            </div>
            <div class="ml-4">
                <el-button type="primary" size="large" @click="searchClick">
                    <HcIcon name="search-2" />
                    <span>搜索</span>
                </el-button>
            </div>
        </template>
        <template #extra>
            <el-button size="large" type="primary" hc-btn @click="addRowClick">
                <HcIcon name="add" />
                <span>新增</span>
            </el-button>
            <el-button size="large" type="danger" hc-btn @click="batchClick">
                <HcIcon name="delete-bin" />
                <span>删除</span>
            </el-button>
        </template>
        <HcTable ref="tableListRef" :column="tableColumn" :datas="tableData" :loading="tableLoading" is-check @selection-change="tableSelectionChange">
            <template #action="{ row, index }">
                <el-button size="small" type="warning" @click="previewPdf(row)">
                    查看附件
                </el-button>
                <el-button size="small" type="primary" @click="editRowClick(row)">
                    编辑
                </el-button>
                <el-button size="small" type="danger" @click="delClickRow(row)">
                    删除
                </el-button>
            </template>
        </HcTable>
        <template #action>
            <HcPages :pages="searchForm" @change="pageChange" />
        </template>

        <!-- 新增/编辑 -->
        <HcDialog is-to-body bg-color="white" :show="rowModal" :title="formModel.id ? '编辑' : '新增'" widths="62rem" :loading="submitLoading" @save="rowModalSave" @close="rowModalClose">
            <el-form ref="formRef" :model="formModel" :rules="formRules" label-position="left" label-width="auto" size="large">
                <div class="flex">
                    <div class="flex-1 mr-4">
                        <el-form-item label="编号" prop="number">
                            <el-input v-model="formModel.number" />
                        </el-form-item>
                        <el-form-item label="名称" prop="name">
                            <el-input v-model="formModel.name" />
                        </el-form-item>
                        <el-form-item label="所属区域：" prop="areaId">
                            <el-select v-model="formModel.areaId" block>
                                <el-option v-for="item in areaType" :key="item.id" :label="item.areaName" :value="item.id" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="多个文件" prop="list">
                            <HcFormUpload v-model="formModel.list" :src="filename" type="list" :preview="false" :is-delete="true" @item="formItemClick" @upload="formItemUpload" @change="formItemChange" />
                        </el-form-item>
                    </div>
                    <div class="flex-1 ml-4">
                        <el-form-item label="备注：">
                            <el-input v-model="formModel.remark" type="textarea" :autosize="{ minRows: 6, maxRows: 10 }" />
                        </el-form-item>
                    </div>
                </div>
            </el-form>
        </HcDialog>

        <HcUploadFile ref="HcUploadFileRef" :options="UploadFileOptions" :params="{ projectId }" @finish="UploadFileFinish" @success="HcUploadFileSuccess" />
    </HcCard>
</template>

<script setup>
import { onActivated, onMounted, ref } from 'vue'
import { getTokenHeader } from '~src/api/request/header'
import policyApi from '~api/base/policy.js'
import { useAppStore } from '~src/store'
import { arrToId, formValidate, getArrValue, getObjValue } from 'js-fast-way'
import { getAllCounty } from '~api/other'
import { delMessageV2 } from '~com/message/index.js'

const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId)
onActivated(()=>{
    getAreaType()
})
onMounted(()=>{
   
    getTableData()
})
//上传配置
const HcUploadFileRef = ref(null)
const UploadFileOptions = {
    headers: getTokenHeader(),
    url:'/api/blade-land/attachmentInfo/add-file',
    accept_tip:'只能上传doc或pdf文件',
    accept:'application/pdf,.doc,.pdf,.docx,application/msword',
}

//项目类型
const areaType = ref([])
//获取区域
const getAreaType = async ()=>{
    const { error, code, data } = await getAllCounty({
        projectId: projectId.value,
    })
    if (!error && code === 200) {
        areaType.value = getArrValue(data)
       
    } else {
        areaType.value = []
    }
}
//搜索表单
const searchForm = ref({
    areaId: null, name: null, startDate: null, endDate: null,
    current: 1, size: 20, total: 0,
})

//搜索
const searchClick = () => {
    searchForm.value.current = 1
    getTableData()
}

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

//获取数据
const tableLoading = ref(false)
const tableColumn = [
    { key: 'number', name: '编号', width: '120' },
    { key: 'name', name: '名称' },
    { key: 'uploadDate', name: '上传日期', width: '140', align: 'center' },
    { key: 'remark', name: '备注', width: '200', isTooltip: true },
    { key: 'action', name: '操作', width: '220', align: 'center' },
]
const tableData = ref([
])

const getTableData = async () => {
    tableLoading.value = true
    const { error, code, data } = await policyApi.getPage({
        ...searchForm.value,
        projectId: projectId.value,
        type:2,
    })
    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 tableListRef = ref(null)
const tableCheckedKeys = ref([])
const tableSelectionChange = (rows) => {
    tableCheckedKeys.value = rows.filter((item) => {
        return (item ?? '') !== ''
    })
}
//弹窗
const rowModal = ref(false)
const formRef = ref(null)
const formModel = ref({ list:[] })
const formRules = {
    number: [{ required: true, message: '请输入编号', trigger: 'blur' }],
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    areaId: [{ required: true, message: '请选择所属区域', trigger: 'change' }],
    remark: [{ required: true, message: '请输入备注', trigger: 'blur' }],
    list:[{ required: true, message: '请上传附件', trigger: 'blur' }],
   
}

//新增
const addRowClick = () => {
    formModel.value = { list:[] }
    rowModal.value = true
    filename.value = ''
}
//查看附件

const previewPdf = (row) => {
  const { pdfUrl } = row
  if (pdfUrl) {
    window.open(pdfUrl, '_blank')
  } else {
    window.$message.warning('文件不存在')
  }
 
}
//编辑
const editRowClick = (row) => {
    getDetail(row.id)
    rowModal.value = true
}
//获取详情
 const getDetail = async (id)=>{
    const { error, code, data } = await policyApi.getDetail({
        id,
    })
    if (!error && code === 200) {
        formModel.value = getObjValue(data)
        const list = formModel.value['list'] || []
        let namearr = []
        list.forEach((ele)=>{
            namearr.push(ele.name)
        })
        filename.value = namearr.join(',')
    } else {
        formModel.value = { list:[] }
        filename.value = ''
    }
 }


//保存
const submitLoading = ref(false)
const rowModalSave = async () => {
    console.log(formModel.value)
    const res = await formValidate(formRef.value)
    if (res) {
        submitLoading.value = true
        //发起请求
        const form = formModel.value
        form.projectId = projectId.value
        form.type = 2
        const { error, code, msg } = await policyApi.addOrUpdate(form)
        //判断状态
        submitLoading.value = false
        if (!error && code === 200) {
            window.$message?.success(msg)
            rowModal.value = false
            getTableData()
            
        } 
    }
}

//关闭弹窗
const rowModalClose = () => {
    rowModal.value = false
    formModel.value = {}
}

//上传
const formItemUpload = () => {
    HcUploadFileRef?.value?.cancelUpload()
    HcUploadFileRef.value?.selectFile()
}


const formItemClick = async ({ item, index }) => {
    console.log(item, 'item')
   
}

//文件变化
const formItemChange = (src, index) => {
    formModel.value.list.splice(index, 1)
}
//文件上传完成
const UploadFileFinish = ()=>{
    HcUploadFileRef?.value.setModalShow(false)
}
const filename = ref('')
// 文件上传成功的回调
const HcUploadFileSuccess = ({ resData }) => {
    formModel.value.list.push(resData)
    const { name } = resData
    if (filename.value) {
        filename.value = filename.value + ',' + name
        
    } else {
        filename.value = name
    }
   
}
//删除
const delClickRow = (row)=>{
    delMessageV2(async (action, instance, done) => {
        if (action === 'confirm') {
            instance.confirmButtonLoading = true
             removeRow([row.id])
            instance.confirmButtonLoading = false
            done()
        } else {
            done()
        }
 })
}
const removeRow = async (id)=>{
    const { error, code } = await policyApi.remove( id, false)
    //判断状态
    if (!error && code === 200) {
        window.$message?.success('删除成功')
        getTableData()
    } else {
        window.$message?.error('删除失败')
    }
}

const batchClick = ()=>{
    const rows = tableCheckedKeys.value
    const ids = arrToId(rows).split(',')
    delMessageV2(async (action, instance, done) => {
        if (action === 'confirm') {
            instance.confirmButtonLoading = true
             removeRow(ids)
            instance.confirmButtonLoading = false
            done()
        } else {
            done()
        }
 })
}
</script>
