<template>
    <el-container class="aminui-main-container">
		<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.purchaseNoLike" 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="采购申请:">
                                    <el-input v-model="params.nameLike" clearable placeholder="请输入采购申请名称"></el-input>
                                </el-form-item>
                            </el-col>
                            <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="8" :md="12" :xs="24">
                                <el-form-item label="计划内采购:">
                                    <el-select v-model="params.isInPlan" clearable placeholder="请选择是否计划内采购">
                                        <el-option label="是" :value="true"></el-option>
                                        <el-option label="否" :value="false"></el-option>
                                    </el-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="12" :xs="24">
                                <el-form-item label="外部律师选聘:">
                                    <el-select v-model="params.isLawyer" clearable placeholder="请选择是否外部律师选聘">
                                        <el-option label="是" :value="true"></el-option>
                                        <el-option label="否" :value="false"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :lg="12" :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">
                    <template v-for="(item, key, index) in stepDic" v-bind:key="index">
                        <el-button v-if="index == 0" type="primary" @click="table_add">发起{{ item }}</el-button>
                        <el-button v-else type="primary" @click="table_handle(key)">{{ item }}</el-button>
                    </template>
                </div>
            </el-header>

            <el-main class="nopadding">
                <scTable class="scTable" ref="table" row-key="id" :apiObj="api" :params="params" :column="column" tableName="applyTable" pageParams="current" applySql @select="select">
                    <el-table-column type="selection" align="center" width="55" :selectable="selectable"></el-table-column>
                    <el-table-column label="序号" type="index" align="center" width="80"></el-table-column>
                    <template #stepStatus="scope">
                        <template v-if="scope.row.step">
                            {{ formatStepStatus(scope.row) }}<sc-status-indicator :type="formatStatus(scope.row[handlerKey(scope.row.step)] || scope.row, 'type')"></sc-status-indicator>
                        </template>
                    </template>
                    <template #planName="scope">{{ scope.row.plan.planName }}</template>
                    <template #type="scope">{{ formatType(scope.row.type) }}</template>
                    <template #specialFeeType="scope">{{ formatSpecialType(scope.row.specialFeeType) }}</template>
                    <template #purchaseType="scope">{{ formatPurchaseType(scope.row.purchaseType) }}</template>
                    <template #isInPlan="scope">{{ formatBoolean(scope.row.isInPlan) }}</template>
                    <template #createTime="scope"><span v-time="scope.row.createTime" format="YYYY-MM-DD"></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 #isLawyer="scope">{{ formatBoolean(scope.row.isLawyer) }}</template>
                    
                    <el-table-column label="是否共用" fixed="right" align="center" width="100">
                        <template #default="scope">
                            <el-switch :model-value="scope.row.isShare" :loading="loading.share" :active-value="0" :inactive-value="1" @change="val => openShareChange(val, scope.row)"></el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column label="是否开启" fixed="right" align="center" width="100">
                        <template #default="scope">
                            <template v-if="scope.row.bidNotice.processState == 'ENDED'">
                                <el-switch :model-value="scope.row.oaStatus" :loading="loading.status" :active-value="0" :inactive-value="1" @change="val => openStatusChange(val, scope.row)"></el-switch>
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" fixed="right" align="center" width="240">
                        <template #default="scope">
                            <template v-if="showBtnGroup(scope.row)">
                                <el-button text @click="table_detail(scope.row)">提交</el-button><el-divider direction="vertical" />
                                <el-button text @click="table_detail(scope.row)">编辑</el-button><el-divider direction="vertical" />
                                <el-button text @click="table_del(scope.row)">删除</el-button><el-divider direction="vertical" />
                            </template>
                            <template v-else>
                                <el-button text @click="table_detail(scope.row)">申请详情</el-button><el-divider direction="vertical" />
                            </template>
                            <el-dropdown trigger="click" @command="table_handle($event, scope.row)">
                                <el-button text>更多</el-button>
                                <template #dropdown>
                                    <el-dropdown-menu>
                                        <template v-for="(item, key, index) in moreDropdown" v-bind:key="index">
                                            <el-dropdown-item :command="key" :divided="index > 0">{{ item }}</el-dropdown-item>
                                        </template>
                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>
                        </template>
                    </el-table-column>
                </scTable>
            </el-main>
        </el-container>
    </el-container>

    <apply-detail v-if="dialog.detail" ref="applyDetail" @success="reloadTable" @closed="dialog.detail = false"></apply-detail>
    <handle-detail v-if="dialog.handle" ref="handleDetail" @success="reloadTable" @closed="dialog.handle = false"></handle-detail>
</template>

<script>
import moment from "moment";
import { column, stepDic } from "./main";
import { statusDic } from "@/views/procurement/plan/main";
import applyDetail from "./detail";
import handleDetail from "./handle";

export default {
    components: {
        applyDetail,
        handleDetail
    },

    data() {
        return {
            column, stepDic,
            api: this.$API.procurement.ledger,
            projects: [],
            purchaseTypes: [],
            specialTypes: [],

            createDate: [],
            params: {
                orderBy: "createTime_desc",
                deptId: null,
                nameLike: null,
                type: null
            },

            paramsIsCollapse: false,
            selectData: null,
            dialog: {
                detail: false,
                handle: false
            },

            loading: {
                status: false,
                share: false
            }
        }
    },

    computed: {
        moreDropdown() {
            const dropdown = {};
            for (const key in stepDic) {
                if (key != "purchase_apply") dropdown[key] = stepDic[key];
            }
            return dropdown;
        },

        depts() {
            return this.$refs.deptTreeSelect && this.$refs.deptTreeSelect.treeList || [];
        },

        dicts() {
            return this.$refs.dictSelect && this.$refs.dictSelect.options || [];
        }
    },

    mounted() {
        this.getProjects();
        this.getPurchaseTypes();
        this.getSpecialTypes();
    },

    methods: {
        handlerKey(mode) {
            const modeArray = mode.split("purchase_")[1].split("_");
            const suffixArray = modeArray.slice(1);
            return modeArray[0] + suffixArray.map(str => this.$TOOL.capitalizeWords(str)).join("");
        },

        formatStepStatus(row) {
            const stepName = stepDic[row.step] || "";
            const statusName = this.formatStatus(row[this.handlerKey(row.step)] || row, "label");
            return stepName && statusName && (stepName + " - " + statusName) || "";
        },

        formatStatus({ status, processState }, key) {
            if (!status) {
                if (processState && key == "label") return "审核终止";
                if (!processState && key == "label") return "待发起审核";
                if (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 || "";
        },

        formatSpecialType(value) {
            return this.specialTypes.find(p => p.value == value) && this.specialTypes.find(p => p.value == value).label || "";
        },

        formatPurchaseType(value) {
            return this.purchaseTypes.find(p => p.value == value) && this.purchaseTypes.find(p => p.value == value).label || "";
        },

        formatBoolean(value) {
            return value && "是" || "否";
        },

        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 || "";
        },

        showBtnGroup(row) {
            if (row.processState == "ENDED") return false;
            for (const key in stepDic) { // 所有过程中不能有已完成
                if (row[this.handlerKey(key)] && row[this.handlerKey(key)].processState == "ENDED") return false;
            }

            return !row.status || (row.status == "active" && row.step == "purchase_apply");
        },

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

        async getPurchaseTypes() {
            const res = await this.$API.system.dictDetail.get({ page: 0, size: 999, dictName: "procurement_type" });
            this.purchaseTypes = res.content;
        },

        async getSpecialTypes() {
            const res = await this.$API.system.dictDetail.get({ page: 0, size: 999, dictName: "special_expenses_type" });
            this.specialTypes = res.content;
        },
        
        // 本地更新数据
        reloadTable(mode = "add") {
            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);
        },

        reset() {
            this.createDate = [];
            for (const key in this.params) {
                if (key != "orderBy") this.params[key] = null;
            }

            this.reloadTable();
        },

        dateChange(type) {
            this.createDate = [moment().startOf(type).format("YYYY-MM-DD"), moment().format("YYYY-MM-DD")];
            this.reloadTable();
        },

        selectable(row) {
            return !this.selectData || this.selectData.id == row.id;
        },

        // 表格勾选事件
        select(rows, row) {
            this.selectData = rows.length && rows.indexOf(row) !== -1 && Object.assign({}, row) || null;
        },

        // 添加申请
        table_add() {
            this.dialog.detail = true;
            this.$nextTick(() => this.$refs.applyDetail.open());
        },

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

        table_handle(command, selected = this.selectData) {
            if (!selected) return this.$notify.warning({ title: "提示", message: "请选择一个采购申请", duration: 1500 });
            
            this.dialog.handle = true;
            this.$nextTick(() => this.$refs.handleDetail.open(command).setData(selected, selected[this.handlerKey(command)]));
        },

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

        // 是否共用
        openShareChange(isShare, { id }) {
            this.loading.share = true;
            this.$API.procurement.apply.updatePurchase({ id, isShare }).then(() => {
                this.loading.share = false;
                this.$message.success("操作成功");
                this.reloadTable("update");
            }).catch(() => this.loading.share = false);
        },

        // oa 情况通知-是否开启
        openStatusChange(status, { id, oaStatus }) {
            if (status === 1 && (oaStatus === undefined || oaStatus === null)) return;

            this.loading.status = true;
            this.$API.auth.oa.updateStatus({ id, status }).then(() => {
                this.loading.status = false;
                this.$message.success("操作成功");
                this.reloadTable("update");
            }).catch(() => this.loading.status = 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%;
      }
    }
  }

  .aminui-main-container__table-main .scTable {
    :deep(.el-table__header) .el-checkbox {
      display: none;
    }
  }
}

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