<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-blue)"><sc-icon-budget-amount /></el-icon>
                <sc-statistic title="年度预算总金额" :value="$TOOL.unifyNumber(census.yearBudgetAmount)" :suffix="suffixUnit(census.yearBudgetAmount)"></sc-statistic>
            </div>
            <div class="statistics-panel">
                <el-icon size="42" color="var(--el-color-primary)"><sc-icon-budget-amount /></el-icon>
                <sc-statistic title="当月预算总金额" :value="$TOOL.unifyNumber(census.monthBudgetAmount)" :suffix="suffixUnit(census.monthBudgetAmount)"></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="业务所属公司:">
                                <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-input v-model="params.planNameLike" 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="采购类别:">
                                    <dict-select ref="dictSelect" v-model="params.type" dic="procurement_category" clearable placeholder="请选择采购类别"></dict-select>
                                </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.budgetAmountBegin" step-strictly :controls="false" placeholder="最小值"></el-input-number>-
                                    <el-input-number v-model="params.budgetAmountEnd" step-strictly :controls="false" placeholder="最大值"></el-input-number>
                                </el-form-item>
                            </el-col>
                            <el-col :lg="10" :md="16" :xs="24">
                                <el-form-item label="计划开始日期:">
                                    <el-date-picker type="daterange" v-model="startDate" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD"></el-date-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :lg="10" :md="16" :xs="24">
                                <el-form-item label="计划完成日期:">
                                    <el-date-picker type="daterange" v-model="endDate" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD"></el-date-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :lg="10" :md="16" :xs="24">
                                <el-form-item label="创建时间:">
                                    <el-date-picker type="daterange" v-model="createDate" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD"></el-date-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :md="8" :xs="24">
                                <el-form-item>
                                    <el-button @click="dateChange('month')">本月</el-button>
                                    <el-button @click="dateChange('year')" >本年</el-button>
                                </el-form-item>
                            </el-col>
                        </template>
                    </el-row>
                </el-form>

                <el-button-group>
                    <el-button type="primary" icon="el-icon-search" @click="reloadTable('add')">查询</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_add">新增计划</el-button>
                </div>
            </el-header>

            <el-main class="nopadding">
                <scTable class="scTable" ref="table" row-key="id" :apiObj="api" :params="params" :column="column" tableName="planTable" pageParams="current" applySql>
                    <el-table-column label="序号" type="index" align="center" width="60"></el-table-column>
                    <template #status="scope">
                        {{ formatStatus(scope.row, "label") }}<sc-status-indicator :type="formatStatus(scope.row, 'type')"></sc-status-indicator>
                    </template>
                    <template #type="scope">{{ formatType(scope.row.type) }}</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>
                    <el-table-column label="操作" fixed="right" align="center" width="200">
                        <template #default="scope">
                            <template v-if="!scope.row.status || scope.row.status == 'active'">
                                <el-button text @click="table_detail(scope.row)">提交</el-button><el-divider direction="vertical" />
                                <el-button text @click="table_detail(scope.row)">编辑</el-button>
                                <template v-if="!scope.row.status">
                                    <el-divider direction="vertical" /><el-button text @click="table_del(scope.row)">删除</el-button>
                                </template>
                            </template>
                            <template v-if="scope.row.status == 'approve' || scope.row.status == 'done'">
                                <el-button text @click="table_detail(scope.row)">详情</el-button>
                            </template>
                        </template>
                    </el-table-column>
                </scTable>
            </el-main>
        </el-container>
    </el-container>
    
    <plan-detail v-if="dialog" ref="planDetail" @success="reloadTable" @closed="dialog = false"></plan-detail>
</template>

<script>
import moment from "moment";
import { column, statusDic } from "./main";
import planDetail from "./detail";

export default {
    components: {
        planDetail
    },

    data() {
        return {
            census: {
                monthBudgetAmount: 0,
                yearBudgetAmount: 0
            },
            projects: [],

            column,
            api: this.$API.procurement.plan,
            params: {
                orderBy: "createTime_desc"
            },
            createDate: [],
            startDate: [],
            endDate: [],

            paramsIsCollapse: false,
            dialog: false
        }
    },

    computed: {
        depts() {
            return this.$refs.deptTreeSelect && this.$refs.deptTreeSelect.treeList || [];
        },
        
        dicts() {
            return this.$refs.dictSelect && this.$refs.dictSelect.options || [];
        }
    },

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

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

        formatStatus({ status, processInstanceId }, key) {
            if (!status && processInstanceId && key == "label") return "审核终止";
            if (!status && !processInstanceId && key == "label") return "待发起审核";
            if (!status && key == "type") return "blue";
            return statusDic[status][key];
        },

        formatType(value) {
            return this.dicts.find(d => d.value == value) && this.dicts.find(d => d.value == value).label || "";
        },

        formatDeptName(value) {
            return this.depts && this.depts.find(d => d.deptId == value) && this.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 || "";
        },

        async getProjects() {
            this.projects = await this.$API.system.project.all({ orderBy: "id_desc", projectStatus: "active" });
        },

        async getCensus() {
            const query = {
                yearCreateTimeBegin: moment().startOf("year").format("YYYY-MM-DD HH:mm:ss"),
                yearCreateTimeEnd: moment().endOf("day").format("YYYY-MM-DD HH:mm:ss"),
                monthCreateTimeBegin: moment().startOf("month").format("YYYY-MM-DD HH:mm:ss"),
                monthCreateTimeEnd: moment().endOf("day").format("YYYY-MM-DD HH:mm:ss")
            }
            if (this.$TOOL.data.get("APPLY_SQL")) query["applySql"] = this.$TOOL.data.get("APPLY_SQL");

            const res = await this.$API.procurement.plan.getTongji(query);
            this.census.yearBudgetAmount = res && res.yearBudgetAmount || 0;
            this.census.monthBudgetAmount = res && res.monthBudgetAmount || 0;
        },

        // 本地更新数据
        reloadTable(mode = "add") {
            this.params["beginDateBegin"] = this.startDate && this.startDate[0] && this.startDate[0] || "";
            this.params["beginDateEnd"] = this.startDate && this.startDate[1] && this.startDate[1] || "";
            this.params["endDateBegin"] = this.endDate && this.endDate[0] && this.endDate[0] || "";
            this.params["endDateEnd"] = this.endDate && this.endDate[1] && this.endDate[1] || "";
            this.params["createTimeBegin"] = this.createDate && this.createDate[0] && (this.createDate[0] + " 00:00:00") || "";
            this.params["createTimeEnd"] = this.createDate && this.createDate[1] && (this.createDate[1] + " 23:59:59") || "";
            
            const page = mode == "add" && 1 || this.$refs.table.currentPage;
            this.$refs.table.reload(this.params, page);
            (mode == "add" || mode == "edit") && this.getCensus();
        },

        reset() {
            this.createDate = [];
            this.params = {
                orderBy: "createTime_desc"
            }

            this.reloadTable();
        },

        dateChange(type) {
            this.createDate = [moment().startOf(type).format("YYYY-MM-DD"), moment().format("YYYY-MM-DD")];
            this.reloadTable();
        },
        
        // 添加计划
        table_add() {
            this.dialog = true;
            this.$nextTick(() => this.$refs.planDetail.open());
        },

        // 计划编辑/详情/审批流
        table_detail(row) {
            this.dialog = true;
            this.$nextTick(() => this.$refs.planDetail.open("edit").setData(row));
        },

        // 删除计划
        table_del({ id }) {
            this.$confirm("确认删除当前采购计划吗？", "提示", {
                type: "warning",
                confirmButtonText: "删除"
            }).then(() => {
                this.$API.procurement.plan.del({ id }).then(() => {
                	this.$message.success("操作成功");
                	this.reloadTable();
                }).catch(() => {});
            }).catch(() => {});
        }
    }
}
</script>

<style lang="scss" scoped>
.aminui-main-container {
  .aminui-main-container__statistics-header {
    .statistics-panel:first-child .sc-statistic :deep(.sc-statistic-content) {
      color: var(--el-color-blue);
    }

    .statistics-panel:last-child .sc-statistic :deep(.sc-statistic-content) {
      color: var(--el-color-primary);
    }
  }

  .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%;
      }
    }
  }
}

@media (max-width: 992px) {
  .aminui-main-container .aminui-main-container__query-header {
    padding-bottom: 18px;
  }
}
</style>