<template>
    <el-container class="aminui-main-container">
        <el-header class="aminui-main-container__statistics-header">
            <div class="statistics-panel">
                <el-icon size="42" color="var(--el-color-success)"><sc-icon-contract-amount /></el-icon>
                <sc-statistic title="合同金额" :value="$TOOL.unifyNumber(census.contractAmount)" :suffix="suffixUnit(census.contractAmount)"></sc-statistic>
            </div>
            <div class="statistics-panel">
                <el-icon size="42" color="var(--el-color-success)"><sc-icon-budget-amount /></el-icon>
                <sc-statistic title="预算金额" :value="$TOOL.unifyNumber(census.purchaseAmount)" :suffix="suffixUnit(census.purchaseAmount)"></sc-statistic>
            </div>
            <div class="statistics-panel">
                <el-icon size="42" color="var(--el-color-success)"><sc-icon-amount /></el-icon>
                <sc-statistic title="控制价" :value="$TOOL.unifyNumber(census.controlAmount)" :suffix="suffixUnit(census.controlAmount)"></sc-statistic>
            </div>
            <div class="statistics-panel">
                <el-icon size="42" color="var(--el-color-success)"><sc-icon-bid-amount /></el-icon>
                <sc-statistic title="中标金额" :value="$TOOL.unifyNumber(census.bidAmount)" :suffix="suffixUnit(census.bidAmount)"></sc-statistic>
            </div>
        </el-header>

		<el-header class="aminui-main-container__query-header">
            <el-scrollbar>
                <el-form :model="params">
                    <el-row :gutter="15">
                        <el-col :lg="8" :md="12" :xs="24">
                            <el-form-item label="发起人所属公司:">
                                <tree-select ref="deptTreeSelect" v-model="params.deptId" :apiObj="$API.system.dept" isDept isAllDept check-strictly clearable placeholder="请选择发起人所属公司"></tree-select>
                            </el-form-item>
                        </el-col>
                        <el-col :lg="8" :md="12" :xs="24">
                            <el-form-item label="采购申请编号:">
                                <el-input v-model="params.purchaseNoLike" clearable placeholder="请输入采购申请编号"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :lg="8" :md="12" :xs="24">
                            <el-form-item label="采购申请名称:">
                                <el-input v-model="params.nameLike" clearable placeholder="请输入采购申请名称"></el-input>
                            </el-form-item>
                        </el-col>
                        <template v-if="paramsIsCollapse">
                            <el-col :lg="8" :md="12" :xs="24">
                                <el-form-item label="业务所属公司:">
                                    <tree-select v-model="params.belongDeptId" :apiObj="$API.system.dept" isDept isAllDept check-strictly clearable placeholder="请选择业务所属公司"></tree-select>
                                </el-form-item>
                            </el-col>
                            <el-col :lg="8" :md="12" :xs="24">
                                <el-form-item label="项目名称:">
                                    <el-select v-model="params.projectId" filterable placeholder="请选择项目">
                                        <el-option v-for="item in projects" :key="item.id" :label="item.projectName" :value="item.id"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :lg="8" :md="12" :xs="24">
                                <el-form-item label="合同编号:">
                                    <el-input v-model="params.contractNo" clearable placeholder="请输入合同编号"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :lg="8" :md="12" :xs="24">
                                <el-form-item label="合同名称:">
                                    <el-input v-model="params.contractName" clearable placeholder="请输入合同名称"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :lg="10" :md="12" :xs="24">
                                <el-form-item class="amount-range-item" label="合同金额:">
                                    <el-input-number v-model="params.signAmountBegin" step-strictly :controls="false" placeholder="最小值"></el-input-number>-
                                    <el-input-number v-model="params.signAmountEnd" step-strictly :controls="false" placeholder="最大值"></el-input-number>
                                </el-form-item>
                            </el-col>
                            <template v-for="(item, key) in queryDatePicker" v-bind:key="key">
                                <el-col :lg="12" :md="16" :xs="24">
                                    <el-form-item :label="`${item.label}:`">
                                        <el-date-picker v-model="item.modelValue" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD"></el-date-picker>
                                    </el-form-item>
                                </el-col>
                            </template>
                        </template>
                    </el-row>
                </el-form>

                <el-button-group>
                    <el-button type="primary" icon="el-icon-search" @click="reloadTable">查询</el-button>
                    <el-button icon="el-icon-refresh" @click="reset">重置</el-button>
                    <el-button text @click="paramsIsCollapse = !paramsIsCollapse">
                        <template v-if="paramsIsCollapse">收起<el-icon><el-icon-arrow-up-bold /></el-icon></template>
                        <template v-else>更多<el-icon><el-icon-arrow-down-bold /></el-icon></template>
                    </el-button>
                </el-button-group>
            </el-scrollbar>
        </el-header>

        <el-container class="aminui-main-container__table-main">
            <el-header>
                <div class="left-panel">
                    <el-button type="primary" @click="table_export">导出</el-button>
                </div>
            </el-header>

            <el-main class="nopadding">
                <scTable class="scTable" ref="table" row-key="id" :apiObj="api" :params="params" :column="column" tableName="ledgerTable" pageParams="current" applySql>
                    <el-table-column label="序号" type="index" align="center" width="60"></el-table-column>
                    <el-table-column type="expand" width="1">
                        <template #default="scope">
                            <el-table :data="scope.row.contractList">
                                <template v-for="(item, index) in contractColumn" v-bind:key="index">
                                    <el-table-column :label="item.label" :prop="item.prop" align="center" show-overflow-tooltip>
                                        <template #default="scope_c">
                                            <span v-if="item.prop.includes('Time')" v-time="scope_c.row[item.prop]" format="YYYY-MM-DD"></span>
                                        </template>
                                    </el-table-column>
                                </template>
                                <!-- <el-table-column label="合同附件" align="center" show-overflow-tooltip>
                                    <template #default="scope_c">
                                        <el-button :loading="downloadLoading" text @click="downloadFile(scope_c.row)">{{ scope_c.row.fileName }}</el-button>
                                    </template>
                                </el-table-column> -->
                            </el-table>
                        </template>
                    </el-table-column>

                    <template #contract="scope">
                        <span :class="['table-row-expand-icon', scope.row.isExpand && 'expanded' || 'collapsed']" @click="toggleContract(scope.row)"></span>
                    </template>
                    <template #deptName="scope">{{ formatDeptName(scope.row.deptId) }}</template>
                    <template #belongDeptName="scope">{{ formatDeptName(scope.row.belongDeptId) }}</template>
                    <template #projectName="scope">{{ formatProjectName(scope.row.projectId) }}</template>
                    <template #purchaseType="scope">{{ formatDictName("types", scope.row.purchaseType) }}</template>
                    <template #purchasingAgent="scope">{{ scope.row.bidSign.bidSign || scope.row.matter.createName }}</template>
                    <template #bidNotice_bidAmount="scope">{{ formatObjValue("bidNotice_bidAmount", scope.row) }}</template>
                    <template #bidNotice_controlAmount="scope">{{ formatObjValue("bidNotice_controlAmount", scope.row) }}</template>
                    <template #bidNotice_bidAgency="scope">{{ formatDictName("agencys", formatObjValue("bidNotice_bidAgency", scope.row)) }}</template>
                    <template #bidNotice_bidPlatform="scope">{{ formatDictName("platforms", formatObjValue("bidNotice_bidPlatform", scope.row)) }}</template>
                    <template v-slot:behind>
                        <template v-for="(item, key, index) in queryDatePicker" v-bind:key="index">
                            <el-table-column v-if="!item.tableHide" :label="item.label" align="center" width="140">
                                <template #default="scope"><span v-time="formatObjValue(key, scope.row)" format="YYYY-MM-DD"></span></template>
                            </el-table-column>
                        </template>
                    </template>
                    <el-table-column label="操作" fixed="right" align="center" width="140">
                        <template #default="scope">
                            <el-button text @click="table_detail(scope.row)">详情</el-button>
                        </template>
                    </el-table-column>
                </scTable>
            </el-main>
        </el-container>
    </el-container>

    <ledger-detail v-if="dialog" ref="ledgerDetail" @closed="dialog = false"></ledger-detail>
</template>

<script>
import { exportExcel } from "@/utils/exportExcel";
import { column, contractColumn, queryDatePicker, formatExcel } from "./main";
import ledgerDetail from "./detail";

export default {
    components: {
        ledgerDetail
    },

    data() {
        return {
            column, contractColumn, queryDatePicker,
            projects: [],
            types: [],
            platforms: [],
            agencys: [],
         
            census: {
                contractAmount: 0,
                purchaseAmount: 0,
                controlAmount: 0,
                bidAmount: 0
            },
            api: this.$API.procurement.ledger,
            params: {
                orderBy: "createTime_desc"
            },

            paramsIsCollapse: false,
            dialog: false,
            
            downloadLoading: false
        }
    },

    mounted() {
        this.getProjects();
        this.getDicts();
        this.getCensus();
    },

    methods: {
        suffixUnit(value) {
            return value >= 10000 && "万" || "元";
        },

        formatDeptName(value) {
            const depts = this.$refs.deptTreeSelect && this.$refs.deptTreeSelect.treeList || [];
            return depts && depts.find(d => d.deptId == value) && depts.find(d => d.deptId == value).name || "";
        },

        formatProjectName(value) {
            return this.projects && this.projects.find(d => d.id == value) && this.projects.find(d => d.id == value).projectName || "";
        },

        formatDictName(arrayKey, value) {
            return this[arrayKey] && this[arrayKey].find(d => d.value == value) && this[arrayKey].find(d => d.value == value).label || "";
        },

        formatObjValue(objKey, row) {
            if (objKey.includes("_")) {
                const [obj, key] = objKey.split("_");
                return row[obj] && row[obj][key] || "";
            }
            return row[objKey] || "";
        },

        async getProjects() {
            this.projects = await this.$API.system.project.all({ orderBy: "id_desc", projectStatus: "active" });
        },
        
        async getDicts() {
            const resPlatforms = await this.$API.system.dictDetail.get({ page: 0, size: 999, dictName: "bidding_platform" });
            const resAgency = await this.$API.system.dictDetail.get({ page: 0, size: 999, dictName: "bidding_agency" });
            const resType = await this.$API.system.dictDetail.get({ page: 0, size: 999, dictName: "procurement_type" });
            this.platforms = resPlatforms.content;
            this.agencys = resAgency.content;
            this.types = resType.content;
        },

        async getCensus() {
            const query = {};
            if (this.$TOOL.data.get("APPLY_SQL")) query["applySql"] = this.$TOOL.data.get("APPLY_SQL");

            const res = await this.$API.procurement.ledger.getTongji(query);
            this.census.contractAmount = res && res.contractAmount || 0;
            this.census.purchaseAmount = res && res.purchaseAmount || 0;
            this.census.controlAmount = res && res.controlAmount || 0;
            this.census.bidAmount = res && res.bidAmount || 0;
        },

        // 本地更新数据
        reloadTable() {
            for (const key in this.queryDatePicker) {
                const [start, end] = key.split("_");
                this.params[`${start + this.$TOOL.capitalizeWords(end)}Begin`] = this.queryDatePicker[key].modelValue && this.queryDatePicker[key].modelValue[0] && (this.queryDatePicker[key].modelValue[0] + " 00:00:00") || null;
                this.params[`${start + this.$TOOL.capitalizeWords(end)}End`] = this.queryDatePicker[key].modelValue && this.queryDatePicker[key].modelValue[1] && (this.queryDatePicker[key].modelValue[1] + " 23:59:59") || null;
            }
            this.$refs.table.reload(this.params, 1);
            this.getCensus();
        },

        reset() {
            for (const key in this.queryDatePicker) {
                this.queryDatePicker[key].modelValue = null;
            }
            this.params = { orderBy: "createTime_desc" };
            this.reloadTable();
        },
        
        // 台账详情
        table_detail(row) {
            this.dialog = true;
            this.$nextTick(() => this.$refs.ledgerDetail.open().setData(row));
        },

        toggleContract(row) {
            this.$refs.table.toggleRowExpansion(row, !row.isExpand);
            row.isExpand = !row.isExpand;
        },

        table_export() {
            let exportList = this.$refs.table.$refs.scTable.data.map(item => item.contractList.map(c => ({ ...c, purchase: Object.assign({}, item) })))
            if (exportList.length) exportList = exportList.reduce((p, v) => p.concat(v));
            
            const header = formatExcel();
            const merges = formatExcel("prop").map((_, c) => ({ s: { r: 1, c }, e: { r: exportList.length, c } })).toSpliced(2, 6);
            const data = exportList.map(v => formatExcel("prop").map(j => {
                if (j.includes("purchase_")) {
                    const p_key = j.split("purchase_")[1];
                    if (p_key == "deptName") return this.formatDeptName(v["purchase"].deptId);
                    else if (p_key == "belongDeptName") return this.formatDeptName(v["purchase"].belongDeptId);
                    else if (p_key == "projectName") return this.formatProjectName(v["purchase"].projectId);
                    else if (p_key == "purchaseType") return this.formatDictName("types", v["purchase"].purchaseType);
                    else if (p_key == "purchasingAgent") return v["purchase"].bidSign.bidSign || v["purchase"].matter.createName;
                    else if (p_key == "bidNotice_bidAgency") return this.formatDictName("agencys", this.formatObjValue(p_key, v["purchase"]));
                    else if (p_key == "bidNotice_bidPlatform") return this.formatDictName("platforms", this.formatObjValue(p_key, v["purchase"]));
                    else return p_key.includes('Time') && this.formatObjValue(p_key, v["purchase"]).split(" ")[0] || this.formatObjValue(p_key, v["purchase"]);
                }
                return j.includes('Time') && v[j].split(" ")[0] || v[j];
            }));
            exportExcel(header, data, merges, "招标台账.xlsx");
        },

        // async downloadFile({ objectId, fileName }) {
        //     try {
        //         this.downloadLoading = true;
        //         const res = await this.$API.procurement.contract.download({ objectId, fileName });
        //         this.downloadLoading = false;
        //         const a = document.createElement("a");
        //         a.href = URL.createObjectURL(res);
        //         a.download = fileName;
        //         a.click();
        //     } catch (error) {
        //         this.downloadLoading = false;
        //     }
        // }
    }
}
</script>

<style lang="scss" scoped>
.aminui-main-container {
  .aminui-main-container__query-header {
    max-height: 218px;
    display: block;

    :deep(.el-scrollbar__view) {
      display: flex;
    }

    .amount-range-item :deep(.el-form-item__content) {
      display: flex;
      justify-content: space-between;

      .el-input-number {
        flex-basis: 40%;
      }
    }
  }

  .scTable :deep(.el-table__body) {
    .table-row-expand-icon {
      display: inline-block;
      width: 17px;
      height: 17px;
      background: #fff;
      border: 1px solid #e8e8e8;
      text-align: center;
      line-height: 13px;
      cursor: pointer;
      user-select: none;
    }

    .expanded::after {
      content: "-";
    }

    .collapsed::after {
      content: "+";
    }

    .el-table__cell.el-table__expand-column .cell {
      display: none;
    }

    .el-table__cell.el-table__expanded-cell .el-table {
      width: 1120px;
    }
  }
}

@media (max-width: 992px) {
  .aminui-main-container .aminui-main-container__query-header {
    padding-bottom: 18px;
    max-height: unset;

    :deep(.el-scrollbar__view) {
      display: block;
      width: calc(100% - 15px);
    }
  }
}
</style>