<script lang="ts">
import { Component } from 'vue-property-decorator';
import template from "./rules.component.html"
import BaseRecordComponent from "hbt-common/components/common/baseRecord.component.vue"
import FormComponent from "hbt-common/components/common/form.component.vue"
import TableComponent from "hbt-common/components/common/table.component.vue"
import FormOption from "hbt-common/models/formOptions"
import BtnOption from "hbt-common/models/btnOptions"
import DrawComponent from '@/components/draw.component.vue';
import TableService from '@/service/table.service';
import UnitService from '@/service/unit.service';
import AreaService from '@/service/area.service';
import RuleService from '@/service/rule.service';
@Component({
    template,
    components: {
        FormComponent,
        TableComponent,
        DrawComponent,
    },
})
export default class RulesManagerComponent extends BaseRecordComponent<any> {
    public tableService = new TableService();
    public unitService = new UnitService()
    public areaService = new AreaService()

    public ruleService = new RuleService()

    public params = {} as any;

    public isReadonly = false;

    public subIsReadonly = false;
    public isManager = true;

    public areaList = [];
    public unitList = [];

    public formActions = [{
        name: "查询",
        value: "search",
        icon: "el-icon-search",
        type: "primary"
    }, {
        name: "清空",
        icon: "el-icon-tickets",
        value: "reset"
    }];

    public tableActions = [{
        name: "添加",
        value: "add",
        icon: "el-icon-plus",
        type: "primary"
    }, {
        name: "批量删除",
        value: "delete",
        plain: true,
        icon: "el-icon-delete",
        type: "danger"
    }];
    public updateTableActions = [{
        name: "添加",
        value: "subAdd",
        plain: true,
        icon: "el-icon-plus",
        type: "success"
    }, {
        name: "批量删除",
        value: "subDelete",
        plain: true,
        icon: "el-icon-delete",
        type: "danger"
    }, {
        name: "批量添加",
        value: "subMutilAdd",
        icon: "el-icon-plus",
        type: "primary"
    }];
    public footerActions = [{
        name: "选择全部",
        value: "selectAll",
        type: "primary"
    }, {
        name: "反向选择",
        value: "reverse"
    }];
    public formOptions: FormOption<BtnOption>[] = [{
        name: "检查表名称",
        key: "name",
        type: "text"
    }];
    public mutilAddOptions: FormOption<BtnOption>[] = [];

    public showUpdate = false;
    public currentId = -1;
    public updateParams = {
        units: [],
        tableItems: []
    } as any;
    public subUpdateParams = {} as any;
    public updateOptions: FormOption<BtnOption>[] = [];
    public updateTableData = { datas: [] };
    public updateTableColumn = [] as any;
    public showSubUpdate = false;
    public showSubMutilUpdate = false;
    public ruleParams = {
        pageSize: 10,
        pageNum: 1
    }

    public updateActions = [] as any;

    public checkUpdateActions = [] as any;

    public subUpdateOptions = [] as any;
    //检查对象
    public analControlList = [] as any;
    //检查对象名称集合
    public analControlNameList = [] as any;

    public subUpdateActions = [{
        name: "取消",
        value: "cancel"
    }, {
        name: "确定",
        value: "saveSub",
        type: "primary"
    }];

    public selectData = [];


    created() {
        this.loadAreaData();
        this.loadRuleTable();
    }

    public loadRuleTable(num?, type?) {
        if (type && num) {
            this.ruleParams[type] = num
        } else {
            this.ruleParams = {
                pageSize: 10,
                pageNum: 1
            }
        }
        this.ruleService.selectByPage(this.ruleParams).then((res: any) => {
            this.updateTableData = res.data;
            this.updateTableData.datas.forEach((item: any, index) => {
                item.index = index + 1;
            })
        })
    }

    public buildUpdateForm() {

        this.mutilAddOptions = [{
            name: "检查项目",
            key: "name",
            type: "text"
        }, {
            name: "类型",
            key: "type",
            clearable: true,
            type: "select",
            datas: this.$store.state.prevention.prevention_dangrous_type
        }]
        this.updateOptions = [{
            name: "检查表编号",
            key: "number",
            type: "text",
            width: "calc(50% - 20px)",
            require: true,
            disable: true,
        }, {
            name: "检查表名称",
            key: "name",
            type: "text",
            width: "calc(50% - 20px)",
            require: true,
            showError: false,
        }, {
            name: "适用区域",
            key: "areas",
            type: "select",
            multiple: true,
            width: "calc(50% - 20px)",
            require: true,
            showError: false,
            datas: this.areaList,
            clearable: true,
        }, {
            name: "适用单元",
            key: "units",
            type: "select",
            multiple: true,
            width: "calc(50% - 20px)",
            require: true,
            showError: false,
            datas: this.unitList,
            clearable: true,
        }, {
            name: "适用对象",
            key: "targets",
            format: "analControlNames",
            type: "select",
            multiple: true,
            width: "calc(50% - 20px)",
            require: true,
            showError: false,
            datas: this.$store.state.prevention.analControlList,
            clearable: true,
        }, {
            name: "适用部门",
            key: "depts",
            multiple: true,
            type: "treeSelect",
            datas: this.$store.state.prevention.deptTreeList,
            expandLevel: Infinity,
            width: "calc(50% - 20px)",
            require: true,
            showError: false,
            // datas: this.$store.state.prevention.deptList,
            clearable: true,
        }, {
            name: "适用类型",
            key: "types",
            format: "typesName",
            type: "select",
            width: "calc(50% - 20px)",
            require: true,
            multiple: true,
            showError: false,
            datas: this.$store.state.prevention.prevention_dangrous_type,
            clearable: true,
        }]
        this.updateActions = [{
            name: "取消",
            value: "cancel"
        }, {
            name: "保存并继续添加",
            value: "saveAndContinue",
            type: "primary",
            hide: this.updateParams.id
        }, {
            name: "保存",
            value: "save",
            type: "primary"
        }];
    }

    public subBuildUpdateForm() {
        this.subUpdateOptions = [{
            name: "检查项目",
            type: "text",
            require: true,
            showError: false,
            width: "100%",
            key: "name",
        }, {
            name: "检查内容",
            type: "textarea",
            require: true,
            width: "100%",
            showError: false,
            key: "content",
        }, {
            name: "检查依据",
            type: "textarea",
            require: true,
            width: "100%",
            showError: false,
            key: "reason",
        }]
        this.checkUpdateActions = [{
            name: "取消",
            value: "cancel"
        }, {
            name: "保存并继续添加",
            value: "saveAndContinue",
            type: "primary",
            hide: this.subUpdateParams.index
        }, {
            name: "保存",
            value: "save",
            type: "primary"
        }];
    }

    // 加载区域列表
    public loadAreaData() {
        this.areaService.selectByPage({ pageSize: 1000 }).then((res: any) => {
            this.areaList = res.data.datas.map(item => {
                if (item.name) {
                    return {
                        name: item.name,
                        value: item.id
                    }
                }
            });
        })
    }
    // 加载单元列表
    public loadUnitData(ids?, isVerify = false) {
        if (!ids || ids.length === 0) {
            this.unitList = []
            const option = this.updateOptions.find(item => item.key === "units") as any;
            option.datas = this.unitList
            return
        }
        this.unitService.getListByIds({ areaIds: ids }, false).then((res: any) => {
            this.unitList = res.data.map(item => {
                if (item.name) {
                    return {
                        name: item.name,
                        value: item.id
                    }
                }
            });
            const option = this.updateOptions.find(item => item.key === "units") as any;
            option.datas = this.unitList;
            if (isVerify) {
                //单元是否删除
                const isDeleteUnit = this.judgeDeleteUnitMethod(this.updateParams);
                if (!isDeleteUnit) {
                    this.loadAnalControlList(this.updateParams.units, true)
                }
            }
        })
    }

    //加载检查对象
    public loadAnalControlList(ids?, isVerify = false) {
        if (!ids || ids.length === 0) {
            this.analControlList = [];
            this.analControlNameList = [];
            const option = this.updateOptions.find(item => item.key === "targets") as any;
            if (option) {
                option.datas = this.analControlList;
            }
            return
        }
        return new Promise<void>((resove, reject) => {
            this.areaService.getAnalControls(ids).then((res: any) => {
                this.analControlList = res.data.map((item) => {
                    this.analControlNameList[item.value] = item.name
                    return item
                })
                const option = this.updateOptions.find(item => item.key === "targets") as any;
                if (option) {
                    option.datas = this.analControlList;
                }
                if (isVerify) {
                    this.judgeAnalControl(this.updateParams)
                }
                resove()
            })
        })
    }

    public getNumber() {
        this.tableService.getNumber().then(res => {
            this.updateParams.number = res.data
        })
    }

    public buildTable() {
        this.tableColumn = [];
        this.tableColumn.push({ name: '检查表名称', key: "name" });
        this.tableColumn.push({ name: '适用区域', key: "areas" });
        this.tableColumn.push({ name: '适用单元', key: "units" });
        this.tableColumn.push({ name: '适用对象', key: "analControlNames" });
        this.tableColumn.push({ name: '适用部门', key: "depts" });
        this.tableColumn.push({
            name: '适用类型', key: "types", filters: this.$store.state.prevention.prevention_dangrous_type.map(item => {
                return {
                    text: item.name,
                    value: item.name,
                }
            }), filterMethod: (data, row) => {
                return row.types.indexOf(data) >= 0;
            }, render: (data) => {
                return data.types.split(',').map(item => {
                    return this.$store.getters.prevention_dangrous_type_map[item]
                }).join(",")
            }
        });
        this.tableColumn.push({ name: '编制人', key: "createName" });
        this.tableColumn.push({ name: '编制时间', key: "createTime" });
        this.updateTableColumn = [];

        this.updateTableColumn.push({ name: '序号', key: "index", width: "60px" });
        this.updateTableColumn.push({ name: '检查项目', key: "name", showTip: true });
        this.updateTableColumn.push({ name: '检查内容', key: "content", showTip: true });
        this.updateTableColumn.push({ name: '检查依据', key: "reason", showTip: true });
        if (this.showSubMutilUpdate) {
            this.updateTableColumn.push({
                name: '检查类型', key: "type", render: (data) => {
                    return this.$store.getters.prevention_dangrous_type_map[data.type]
                }
            });
        }
    }

    public change(data, item) {
        // 区域
        if (item && item.key === "areas") {
            if (this.updateParams.units.length) {
                this.updateParams.units = [];
            }

            this.loadUnitData(data)
        }
        //检查单元
        if (item && item.key === 'units') {
            if (data.length === 0) {
                this.updateParams.targets = []
            }
            this.loadAnalControlList(data)
        }
    }

    public callback(data, type?) {
        if (type) {
            if (type === 'pageSize' || type === 'pageNum') {
                this.params[type] = data;
            }
            this.getTableData();
            return
        }
        // 查询
        if (data && data.value === "search") {
            this.getTableData()
            // 重置
        } else if (data && data.value === "reset") {
            this.reset()
            // 反选
        } else if (data && data.value === "reverse") {
            this.toggleAll()
            // 全选
        } else if (data && data.value === "selectAll") {
            this.selectAll()
        } else if (data && data.value === "add") {
            this.showUpdateModel()
        } else if (data && data.value === "delete") {
            this.deleteData(this.selectData.map((item: any) => item.id))
        } else if (data && data.value.indexOf("save") >= 0) {
            this.doSave(data.value !== "save")
        } else if (data && data.value === "cancel") {
            this.handleClose()
        }
    }

    public subChange(data, item) {
        //
    }

    public subCallback(data) {
        if (data && data.value === "subAdd") {
            this.showSubUpdateModel()
        } else if (data && data.value.indexOf("save") >= 0) {
            this.doSubSave(data.value !== "save")
        } else if (data && data.value === "cancel") {
            this.handleClose()
        } else if (data && data.value === "subDelete") {
            this.doSubDelete(this.selectData.map((item: any) => item.index - 1))
        } else if (data && data.value === "subMutilAdd") {
            this.showSubMutilUpdate = true;
            this.buildTable()
            this.clearSelect()
            this.loadRuleTable();
        }
    }

    public doMutilAdd() {
        this.selectData.forEach((item: any) => {
            if (!this.updateParams.tableItems.find(itm => itm.id === item.id)) {
                const data = JSON.parse(JSON.stringify(item))
                delete data.id;
                this.updateParams.tableItems.push(data)
            }
        })

        this.updateParams.tableItems.forEach((item, i) => {
            item.index = i + 1
        })
        this.clearSelect()
        this.ruleParams = {
            pageSize: 10,
            pageNum: 1
        }
        this.showSubMutilUpdate = false;
        this.buildTable();
    }

    public cancelMutilAdd() {
        this.clearSelect();
        this.ruleParams = {
            pageNum: 1,
            pageSize: 10,
        }
        this.showSubMutilUpdate = false;
        this.buildTable();

    }

    public clearSelect() {
        (this.$refs.multipleTable as any).clearSelection();
        this.selectData = [];
    }
    // 重置数据
    public reset() {
        this.params = {
            name: "",
            pageNum: 1,
            pageSize: 20,
        } as any;

        this.ruleParams = {
            pageNum: 1,
            pageSize: 10,
        }
        this.getTableData()
    }

    public showSubUpdateModel(row?, isRead?) {
        this.subUpdateParams = {} as any;
        this.subIsReadonly = !!isRead;
        if (row) {
            this.subUpdateParams = JSON.parse(JSON.stringify(row))
        }
        this.subBuildUpdateForm()
        this.showSubUpdate = true;
    }

    public showUpdateModel(row?, isRead?) {
        this.updateParams = { number: null, tableItems: [] } as any;
        this.isReadonly = !!isRead;
        this.clearSelect()
        if (!row) {
            this.updateParams = { number: '', units: [], tableItems: [] } as any
            this.currentId = -1;
            this.getNumber();
            this.buildUpdateForm();
            this.showUpdate = true;
        } else {
            this.currentId = row.id;
            this.tableService.selectById(this.currentId, true).then((res: any) => {
                if (isRead) {
                    this.updateParams = Object.assign(res.data, row)
                    this.updateParams.typesName = this.updateParams.types.split(',').map((item) => {
                        item = +item
                        return this.$store.getters.prevention_dangrous_type_map[item]
                    }).join(',')
                } else {
                    this.updateParams = res.data;
                    // 区域是否删除
                    let isDeleteArea = this.judgeDeleteAreaMethod(res);
                    if (!isDeleteArea) {
                        this.loadUnitData(res.data.areas, true);
                    }
                }
                this.updateParams.tableItems.forEach((item, i) => {
                    item.index = i + 1
                })
                this.buildUpdateForm();
                this.showUpdate = true;
            })
        }
    }
    /**
     * 判断区域是否删除
     * @param res 
     */
    public judgeDeleteAreaMethod(res: any) {
        let deleteData = [] as any;
        this.updateParams.areas.forEach((item, index) => {
            const find = this.areaList.find((data: any) => data.value === item);
            if (!find) {
                deleteData.push(item);
            }
        });
        if (deleteData.length > 0) {
            this.updateParams.areas = null;
            this.updateParams.units = null;
            this.updateParams.targets = null;
            this.$confirm(`适用区域信息已变更，请重新选择！`, "", {
                type: 'warning',
                showCancelButton: false,
                closeOnClickModal: false,
            }).then(() => {
                //
            }).catch(() => {
                //
            })

        }

        return !!deleteData.length
    }
    /**
     * 判断单元是否删除
     * @param res 
     */
    public judgeDeleteUnitMethod(paramsData: any) {
        let deleteData = [] as any;
        paramsData.units.forEach((item, index) => {
            const find = this.unitList.find((data: any) => data.value === item);
            if (!find) {
                deleteData.push(item);
            }
        });
        if (deleteData.length > 0) {
            this.updateParams.units = null;
            this.updateParams.targets = null;
            this.$confirm(`适用单元信息已变更，请重新选择！`, "", {
                type: 'warning',
                showCancelButton: false,
                closeOnClickModal: false,
            }).then(() => {
                //
            }).catch(() => {
                //
            })
        }
        return !!deleteData.length
    }

    /**
   * 判断检查对象是否删除
   */
    public judgeAnalControl(paramsData: any) {
        let deleteData = [] as any;
        paramsData.targets.forEach((item, index) => {
            const find = this.analControlList.find((data: any) => data.value === item);
            if (!find) {
                deleteData.push(item);
            }
        });
        if (deleteData.length > 0) {
            this.updateParams.targets = null;
            this.$confirm(`适用对象信息已变更，请重新选择！`, "", {
                type: 'warning',
                showCancelButton: false,
                closeOnClickModal: false,
            }).then(() => {
                //
            }).catch(() => {
                //
            })
        }
        return !!deleteData.length
    }


    public doSubSave(goOn?) {
        if (!this.subUpdateParams.index) {
            this.subUpdateParams.index = this.updateParams.tableItems.length + 1;
            this.updateParams.tableItems.push(this.subUpdateParams);
        } else {
            this.updateParams.tableItems.splice(this.updateParams.tableItems.findIndex(item => item.index === this.subUpdateParams.index), 1, this.subUpdateParams)
        }

        this.updateParams.tableItems.forEach((item, i) => {
            item.index = i + 1
        })
        this.subUpdateParams = {} as any;
        this.showSubUpdate = !!goOn;
    }

    public doSubDelete(indexs) {
        for (let i = this.updateParams.tableItems.length - 1; i >= 0; i--) {
            if (indexs.includes(i)) {
                this.updateParams.tableItems.splice(i, 1)
            }
        }

        this.updateParams.tableItems.forEach((item, i) => {
            item.index = i + 1
        })
        this.clearSelect()
    }

    public doSave(goOn?) {
        this.updateParams.depts = this.updateParams.depts.map(item => {
            return {
                id: item,
                name: this.$store.getters.dept_map[item]
            }
        })

        this.updateParams.targets = this.updateParams.targets.map(item => {
            return {
                id: item,
                name: this.analControlNameList[item]
            }
        })
        this.tableService.addOrUpdate(this.updateParams, this.currentId === -1).then(res => {
            this.$message.success(this.currentId === -1 ? "新增成功！" : "编辑成功");
            this.getTableData();
            this.showUpdate = !!goOn;
            this.updateParams = { areas: [], depts: [], units: [], types: [], targets: [], number: null, tableItems: [] } as any;
            if (!!goOn) {
                this.getNumber();
            }
        }).catch(() => {
            this.updateParams.depts = this.updateParams.depts.map(item => item.id)

            this.updateParams.targets = this.updateParams.targets.map(item => item.id)
        })
    }

    public handleClose() {
        if (this.showSubMutilUpdate) {
            this.showSubMutilUpdate = false;
            this.buildTable();
            return
        }
        if (this.showSubUpdate) {
            this.showSubUpdate = false;
            return
        }
        this.showUpdate = false;
    }


    public toggleAll() {

        this.tableData.datas.forEach((item, index) => {
            (this.$refs.multipleTable as any).toggleRowSelection(item);
        })
    }
    public selectAll() {
        if (!this.selectData.length) {
            this.toggleAll()
        } else {
            this.tableData.datas.forEach((item, index) => {
                const find = this.selectData.find((data: any) => data.id === item.id);
                if (!find) {
                    (this.$refs.multipleTable as any).toggleRowSelection(item);
                }
            })
        }
    }

    public handleSelectionChange(data) {
        this.selectData = data;
    }
}
</script>
<style lang="scss" scoped src="../../common.component.scss"></style>
