<template>
    <div class="hc-page-layout-box">
        <div class="hc-page-content-box">
            <HcNewCard>
                <template #header>
                    <div class="w-60">
                        <el-select v-model="searchForm.type" clearable placeholder="请选择检测类别">
                            <el-option
                                v-for="item in typeData" :key="item.value" :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </div>
                    <div class="ml-2 w-64">
                        <HcDatePicker :dates="betweenTime" clearable @change="betweenTimeUpdate" />
                    </div>
                    <div class="ml-2 w-64">
                        <el-tree-select
                            ref="selectTree"
                            v-model="testId"
                            lazy
                            multiple
                            :load="tesrtreeload"
                            :props="testprops"
                            style="width: 240px"
                            show-checkbox
                            placeholder="请选择试验检测项目名称"
                        />
                    </div>
                    <div class="ml-14">
                        <el-button type="primary" @click="searchClick">
                            <HcIcon name="search-2" />
                            <span>搜索</span>
                        </el-button>
                    </div>
                </template>
                <template #extra>
                    <HcTooltip keys="tentative_collect_monthly_report">
                        <el-button hc-btn type="primary">
                            <HcIcon name="send-plane-2" />
                            <span>上报</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="tentative_collect_monthly_print">
                        <el-button hc-btn color="#567722" :loading="printLoading" @click="printClick">
                            <HcIcon name="printer" />
                            <span>打印</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="tentative_collect_monthly_download">
                        <el-button
                            hc-btn color="#A16222" :loading="downLoading" @click="downClick"
                        >
                            <HcIcon name="download" />
                            <span>下载</span>
                        </el-button>
                    </HcTooltip>
                </template>
                <div class="hc-table-ref-box">
                    <el-table
                        :data="tableData" :span-method="tableSpanMethod" class="hc-table-diy-box" height="100%"
                        style="width: 100%" border
                    >
                        <el-table-column align="right" label="试验组数" width="300">
                            <el-table-column align="left" label="试验项目" prop="title" width="220" />
                            <el-table-column align="center" label="月" prop="month" width="80" />
                        </el-table-column>
                        <el-table-column align="center" label="承包人">
                            <el-table-column align="center" label="合格数" prop="name" />
                            <el-table-column align="center" label="不合格数" prop="state" />
                            <el-table-column align="center" label="备注" prop="zip" />
                        </el-table-column>
                        <el-table-column align="center" label="操作" width="140">
                            <template #default="scope">
                                <!-- scope.row scope.$index -->
                                <HcTooltip keys="tentative_material_approach_annex">
                                    <el-button
                                        plain size="small" type="primary"
                                        @click="editorsNoteModalClick(scope.row)"
                                    >
                                        编辑备注
                                    </el-button>
                                </HcTooltip>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <template #action>
                    <HcPages :pages="searchForm" @change="pageChange" />
                </template>
            </HcNewCard>
        </div>

        <!-- 编辑备注 -->
        <hc-new-dialog v-model="editorsNoteModal" :loading="editorsNoteLoading" title="编辑备注信息" widths="45rem" @close="editorsNoteModalClose" @save="editorsNoteModalSave">
            <el-input v-model="editorsNoteVal" :autosize="{ minRows: 5 }" placeholder="编辑备注信息" type="textarea" />
        </hc-new-dialog>
    </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { useAppStore } from '~src/store'


import queryApi from '~api/data-fill/query'
import { calcDate, downloadBlob, getArrValue, isString } from 'js-fast-way'
import { getDictionary } from '~api/other'
import samplingApi from '~api/tentative/material/sampling'
import { downloadMonth, editRemark, getMonthPage, printMonth } from '~api/tentative/collect/month'
import { toPdfPage } from '~uti/btn-auth'

const useAppState = useAppStore()

//全局变量
const projectId = ref(useAppState.getProjectId)
const contractId = ref(useAppState.getContractId)
const projectInfo = ref(useAppState.getProjectInfo)
const userInfo = ref(useAppState.getUserInfo)
const isCollapse = ref(useAppState.getCollapse)

//监听
watch(() => [
    useAppState.getCollapse,
], ([Collapse]) => {
    isCollapse.value = Collapse
})

//渲染完成
onMounted(() => {
    gettypeData()
})

//树搜索
const isSearchTree = ref(false)
const searchTreeVal = ref('')
const searchTreeData = ref([])

//回车
const treeLoading = ref(false)
const searchTreeKeyUp = (e) => {
    if (e.key === 'Enter') {
        searchTreeClick()
    }
}

const searchTreeClick = async () => {
    if (searchTreeVal.value) {
        isSearchTree.value = true
        treeLoading.value = true
        const { data } = await queryApi.searchContractTree({
            contractId: contractId.value,
            queryValue: searchTreeVal.value,
        })
        //判断状态
        treeLoading.value = false
        searchTreeData.value = getArrValue(data)
    } else {
        treeLoading.value = false
        isSearchTree.value = false
    }
}

const testId = ref()
const selectTree = ref(null)
const tesrtreeload = async (node, resolve) => {
    let parentId = '0'
    if (node.level !== 0) {
        parentId = node?.data?.id
    }
    //获取数据
    const { error, code, data } = await samplingApi.queryLazyTree({
        wbsId:projectInfo.value?.referenceWbsTemplateIdTrial,
        tenantId:  userInfo.value?.tenant_id,
        projectId: projectId.value,
        parentId,
        wbsType: 2,
    })
    //处理数据
    if (!error && code === 200) {
        resolve(getArrValue(data))
    } else {
        resolve([])
    }
}

const testprops = ref({
    label: 'title',
    children: 'children',
    isLeaf: function (data) {
          return !data.hasChildren
    },
})
//搜索表单
const searchForm = ref({
    type: '', contractId: '', endTime: '', startTime:'', ids:'',
    current: 1, size: 20, total: 0,
})
//检测类别
const typeData = ref([])
//检测类别
const gettypeData = async () => {
    const { data } = await getDictionary({
        code: 'trial_detection_category',
    })
    //处理数据
    let newArr = []
    const newData = getArrValue(data)
    for (let i = 0; i < newData.length; i++) {
        newArr.push({
            label: newData[i]['dictValue'],
            value: Number(newData[i]['dictKey']),
        })
    }
    typeData.value = newArr
}
//日期时间被选择
const betweenTime = ref(null)
const betweenTimeUpdate = ({ arr, query }) => {
    const date1 = new Date(arr[0])
    const date2 = new Date(arr[1])
     // 计算两个日期的月份差
    //  const monthDiff = isExactlyOneMonthApart(date1, date2)
    //  console.log(monthDiff, 'monthDiff')
    //  if (!monthDiff) {
    //     window.$message.warning('起始时间必须为1个月')
    //     return
    //  }

    betweenTime.value = arr
    searchForm.value.startTime = arr[0]
    searchForm.value.endTime = arr[1]
}

//搜索
const searchClick = () => {
    searchForm.value.current = 1
    searchForm.value.ids = testId.value.join(',')
    console.log(testId.value, '11111111')
    getTableData()
}

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

//表格合并
const tableSpanMethod = ({ rowIndex, columnIndex }) => {
    if (columnIndex === 0) {
        if (rowIndex % 2 === 0) {
            return {
                rowspan: 2,
                colspan: 1,
            }
        } else {
            return {
                rowspan: 0,
                colspan: 0,
            }
        }
    }
}

//获取数据
const tableLoading = ref(false)
const tableData = ref([])
const getTableData = async () => {
    if (!searchForm.value.type) {
        window.$message.warning('请选择检查类别')
        return
    } else if (!searchForm.value.startTime || !searchForm.value.endTime) {
        window.$message.warning('请选择开始时间和结束时间')
        return
    } else if (!searchForm.value.ids) {
        window.$message.warning('请选择试验检测项目名称')
        return
    }
    tableLoading.value = true
    const { error, code, data } = await getMonthPage({
            ...searchForm.value,
            ids:'1635200237830144002',
            contractId:contractId.value,
        })
        tableLoading.value = false
        //判断状态
        if (!error && code === 200) {
            let resdata = getArrValue(data['records'])
        let arr = []
        resdata.forEach((ele)=>{
            let obj1 = {
                title:ele.trialProjectName,
                month: '本月',
                name: ele.currentMonth.qualifiedTotal,
                state: ele.currentMonth.unQualifiedTotal,
                zip:  ele.currentMonth.remarks,
                recordId:ele.currentMonth.recordId,

            }
            let obj2 = {
                title:ele.trialProjectName,
                month: '累计',
                name: ele.totalMonth.qualifiedTotal,
                state: ele.totalMonth.unQualifiedTotal,
                zip:  ele.totalMonth.remarks,
                recordId:ele.totalMonth.recordId,

            }
            arr.push(obj1)
            arr.push(obj2)
             tableData.value = arr
             searchForm.value.total = data['total']
        })



        } else {
            tableData.value = []
        }
}


//新增/编辑
const editorsNoteModal = ref(false)
const editorsNoteVal = ref('')
const recordId = ref('')
const editorsNoteModalClick = (row) => {
    console.log(row, 'row')
    editorsNoteModal.value = true
    recordId.value = row.recordId


}

//保存
const editorsNoteLoading = ref(false)
const editorsNoteModalSave = async (id) => {
    // editorsNoteModal.value = true
    const { error, code, data, msg } = await editRemark({
        contractId: contractId.value,
        recordId: recordId.value,
        remarks:editorsNoteVal.value,

    })
    //判断状态
    if (!error && code === 200) {
     window.$message.success('操作成功')
     editorsNoteModal.value = false
     getTableData()
    }
}
const editorsNoteModalClose = () => {
    editorsNoteModal.value = false
}

const printLoading = ref(false)
const printClick = async ()=>{
    printLoading.value = true
    if (!searchForm.value.type) {
        window.$message.warning('请选择检查类别')
        return
    } else if (!searchForm.value.startTime || !searchForm.value.endTime) {
        window.$message.warning('请选择开始时间和结束时间')
        return
    } else if (searchForm.value.ids) {
        window.$message.warning('请选择试验检测项目名称')
        return
    }
    const { error, code, data } = await printMonth({
            ...searchForm.value,
            ids:'1635200237830144002',
            contractId:contractId.value,
        })
        printLoading.value = false
        //判断状态
        const res = isString(data) ? data || '' : ''
            if (!error && code === 200 && res) {
                toPdfPage(res)
                //window.open(res, '_blank')
            }

}
const downLoading = ref(false)
const downClick = async ()=>{
    downLoading.value = true
    if (!searchForm.value.type) {
        window.$message.warning('请选择检查类别')
        return
    } else if (!searchForm.value.startTime || !searchForm.value.endTime) {
        window.$message.warning('请选择开始时间和结束时间')
        return
    } else if (searchForm.value.ids) {
        window.$message.warning('请选择试验检测项目名称')
        return
    }
    const { error, code, data } = await downloadMonth({
            ...searchForm.value,
            ids:'1635200237830144002',
            contractId:contractId.value,
        })
        downLoading.value = false
        /*//判断状态
        if (!error) {
        if (disposition) {
            downloadBlob(res, disposition)
        } else {
            window.$message?.error('数据异常')
        }
    }*///判断状态
    const res = isString(data) ? data || '' : ''
    if (!error && code === 200 && res) {
        //toPdfPage(res)
        window.open(res, '_blank')
    }

}
</script>

<style lang="scss" scoped>

</style>

<style lang="scss">
.hc-table-ref-box {
    height: 100%;
    border: 0;
    .el-table.hc-table-diy-box {
        --el-table-bg-color: initial;
        --el-table-header-bg-color: #DAE8F3;
        --el-table-header-text-color: #50545E;
        --el-table-tr-bg-color: #F1F5F8;
        --el-fill-color-light: #e7ebee;
        --el-table-text-color: #666666;
        --el-table-row-hover-bg-color: var(--el-color-primary-light-9);
        &.el-table--border {
            --el-table-border-color: #d7d7d7;
        }
        thead.is-group {
            background: none;
            //表头字体
            tr:first-of-type th:first-of-type,
            tr:first-of-type th:first-of-type {
                .cell {
                    display: inline-flex;
                    font-size: 16px;
                    line-height: initial;
                    position: relative;
                }
            }
            //表头其他样式
            tr:first-of-type th:first-of-type {
                border-bottom: none;
                .cell {
                    top: 7px;
                }
            }
            tr:last-of-type th:first-of-type {
                border-right: 0;
                .cell {
                    top: -7px;
                }
            }
            //斜线
            tr:last-of-type th:nth-of-type(2) {
                .cell {
                    visibility: hidden;
                    line-height: 0;
                    padding: 0;
                }
                &::before, {
                    content: '';
                    position: absolute;
                    width: 1px;
                    height: 308px;
                    background-color: #d7d7d7;
                    display: block;
                    bottom: 0;
                    right: 0;
                    transform: rotate(-75.5deg);
                    transform-origin: bottom;
                }
            }
        }
    }
}
</style>
