
<script lang="ts">
import { Component, Watch } from 'vue-property-decorator';
import template from "./work.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 UnitTreeComponent from '@/components/tree.component.vue';
import WorkService from '@/service/work.service';
import UnitService from '@/service/unit.service';
import AreaService from '@/service/area.service';
import moment from "moment";

@Component({
    template,
    components: {
        FormComponent,
        TableComponent,
        DrawComponent,
        UnitTreeComponent
    },
})
export default class WorkManagerComponent extends BaseRecordComponent<any> {
    public tableService = new WorkService();
    public unitService = new UnitService()
    public areaService = new AreaService()

    public params = {
        areaName: "",
        unitName: "",
        name: ""
    } as any;

    public subTableColumn = [] as any;


    public currentStepTableData = {
        datas: []
    } as any;

    public stepUpdateParams = {} as any;

    public treeData = [] as any;

    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 subTableActions: BtnOption[] = [];
    public footerActions = [{
        name: "选择全部",
        value: "selectAll",
        type: "primary"
    }, {
        name: "反向选择",
        value: "reverse"
    }];
    public formOptions: FormOption<BtnOption>[] = [{
        name: "区域名称",
        key: "areaName",
        type: "text",
    }, {
        name: "单元名称",
        key: "unitName",
        type: "text",
    }, {
        name: "作业活动",
        key: "name",
        type: "text",
    }];

    public showUpdate = false;

    public account = JSON.parse(localStorage.getItem("account") as any);

    public updateParams = {
        identifyTime: moment().format('YYYY-MM-DD'),
        identifyUserId: this.account.userId,
    } as any;

    public selectData = [];

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

    public isReadonly = false;


    public updateOptions: FormOption<BtnOption>[] = [];



    public updateActions = [{
        name: "取消",
        value: "cancel"
    }, {
        name: "保存并继续添加",
        value: "saveAndContinue",
        type: "primary"
    }, {
        name: "保存",
        value: "save",
        type: "primary"
    }];

    public showSubUpdate = false;

    public showSteptable = false;

    public subUpdateOptions: FormOption<BtnOption>[] = [];
    @Watch("$store.state.deptList", { immediate: true, deep: true })
    onChanges() {
        this.loadAreaData()
    }

    created() {
    }

    public buildUpdateForm() {
        this.updateOptions = [{
            name: "选择区域",
            key: "areaId",
            type: "select",
            width: "calc(50% - 20px)",
            require: true,
            format: "areaName",
            showError: false,
            datas: this.areaList
        }, {
            name: "选择单元",
            key: "unitId",
            type: "select",
            format: "unitName",
            width: "calc(50% - 20px)",
            require: true,
            showError: false,
            datas: this.unitList
        }, {
            name: "责任部门",
            key: "chargeDeptId",
            format: "chargeDeptName",
            type: "treeSelect",
            width: "calc(50% - 20px)",
            require: true,
            expandLevel: Infinity,
            showError: false,
            datas: this.$store.state.deptTreeList
        }, {
            name: "责任人",
            key: "chargeUserId",
            format: "chargeUserName",
            type: "select",
            width: "calc(50% - 20px)",
            require: true,
            showError: false,
            datas: this.$store.state.userList
        }, {
            name: "作业名称",
            key: "name",
            type: "text",
            width: "calc(50% - 20px)",
            require: true,
            showError: false,
        }, {
            name: "作业地点",
            key: "location",
            type: "text",
            width: "calc(50% - 20px)",
            require: true,
            showError: false,
        }, {
            showError: false,
            name: "涉及岗位",
            key: "postCode",
            format: "postName",
            type: "select",
            multiple: true,
            width: "calc(50% - 20px)",
            require: true,
            datas: this.$store.state.postList
        }, {
            name: "安全因素",
            key: "safetyFactor",
            format: "safetyFactorName",
            type: "select",
            multiple: true,
            width: "calc(50% - 20px)",
            require: true,
            showError: false,
            datas: this.$store.state.prevention_safe_reason
        }, {
            name: "辨识人",
            key: "identifyUserId",
            format: "identifyUserName",
            type: "select",
            width: "calc(50% - 20px)",
            require: true,
            showError: false,
            datas: this.$store.state.userList
        }, {
            name: "辨识时间",
            key: "identifyTime",
            type: "date",
            subType: "date",
            width: "calc(50% - 20px)",
            require: true,
            showError: false,
            format: "yyyy-MM-dd"
        }];

        this.subTableActions = [{
            name: "添加",
            value: "subAdd",
            icon: "el-icon-plus",
            hide: this.isReadonly,
            type: "primary"
        }, {
            name: "批量删除",
            value: "subDelete",
            plain: true,
            hide: this.isReadonly,
            icon: "el-icon-delete",
            type: "danger"
        }];
        this.subUpdateOptions = [{
            name: "步骤名称",
            key: "name",
            type: "text",
            width: "100%",
            require: true,
            showError: false,
        }, {
            name: "作业步骤描述",
            key: "description",
            type: "textarea",
            width: "100%",
            require: true,
            showError: false,
        }, {
            name: "作业地点",
            key: "location",
            type: "text",
            width: "100%",
            require: true,
            showError: false,
        }, {
            name: "责任人",
            key: "chargeUserId",
            type: "select",
            width: "100%",
            require: true,
            showError: false,
            datas: this.$store.state.userList
        }, {
            name: "作业人",
            key: "workerId",
            type: "select",
            width: "100%",
            require: true,
            showError: false,
            datas: this.$store.state.userList
        }]
    }

    // 加载区域列表
    public loadAreaData() {
        this.areaService.selectByPage({ pageSize: 1000 }).then((res: any) => {
            this.areaList = res.data.datas.map(item => {
                return {
                    name: item.name,
                    value: item.id
                }
            });
            this.buildUpdateForm()
        })
    }
    // 加载单元列表
    public loadUnitData(id?) {
        this.unitService.selectByPage({ pageSize: 1000, areaId: id }, false).then((res: any) => {
            this.unitList = res.data.datas.map(item => {
                return {
                    name: item.name,
                    value: item.id,
                    deptId: item.chargeDeptId,
                    userId: item.chargeUserId,
                    deptName: item.chargeDeptName,
                    userName: item.chargeUserName,
                }
            });
            this.buildUpdateForm()
        })
    }
    // 树点击
    public handleNodeClick(data) {
        this.params.unitName = "";
        this.params.areaName = "";
        if (data.areaId) {
            this.params.unitName = data.name
        } else {
            this.params.areaName = data.name === "全部" ? "" : data.name
        }
        this.getTableData()
    }

    public buildTable() {
        console.log(template);
        
        this.tableColumn.push({ name: '区域名称', key: "areaName", width: "200px" });
        this.tableColumn.push({ name: '风险分析单元', key: "unitName", width: "200px" });
        this.tableColumn.push({ name: '作业活动', key: "name", showTip: true });
        this.tableColumn.push({
            name: '作业步骤', key: "stepNum", render: (data) => {
                return "<span class='link'>" + (data.stepNum ? data.stepNum : 0) + "</span>"
            }
        });
        this.tableColumn.push({ name: '责任部门', key: "chargeDeptName" });
        this.tableColumn.push({ name: '责任人', key: "chargeUserName" });
        this.tableColumn.push({ name: '作业地点', key: "location", showTip: true });
        this.tableColumn.push({ name: '涉及岗位', key: "postName", width: "200px", showTip: true });


        this.subTableColumn.push({ name: '序号', key: "index", width: "60" });
        this.subTableColumn.push({ name: '步骤名称', key: "name" });
        this.subTableColumn.push({ name: '作业步骤描述', key: "description", showTip: true, });
        this.subTableColumn.push({ name: '作业地点', key: "location", showTip: true });
        this.subTableColumn.push({ name: '责任人', key: "chargeUserName" });
        this.subTableColumn.push({ name: '作业人', key: "workerName" });
    }

    public showSteps(el, data) {
        const isTarget = el.target.classList.contains("link");
        if (isTarget) {
            this.showSteptable = true;
            this.currentStepTableData.datas = data.steps.map((item, index) => {
                item.index = index + 1;
                return item
            })
        }
    }

    public changes(data, item) {
        //单元
        if (item && item.key === 'unitId') {
            const unitData = this.unitList.find((itm: any) => itm.value === data) as any;
            this.updateParams.chargeDeptName = unitData.deptName;
            this.updateParams.chargeUserId = unitData.userId;
            this.updateParams.chargeUserName = unitData.userName;
            this.updateParams.chargeDeptId = unitData.deptId;
        }
        // 部门
        if (item && item.key === "chargeDeptId") {
            this.updateParams.chargeDeptName = this.$store.getters.dept_map[data];
        }
        // 新增编辑选择人员
        if (item && item.key === "chargeUserId") {
            if (this.showSubUpdate) {
                this.stepUpdateParams.chargeUserName = this.$store.getters.user_map[data];
                return
            }
            this.updateParams.chargeUserName = this.$store.getters.user_map[data];
        }
        // 新增编辑选择人员
        if (item && item.key === "workerId") {
            this.stepUpdateParams.workerName = this.$store.getters.user_map[data];
        }
        // 辨识人
        if (item && item.key === "identifyUserId") {
            this.updateParams.identifyUserName = this.$store.getters.user_map[data];
        }
        // 区域
        if (item && item.key === "areaId") {
            if (this.updateParams.unitId) {
                this.updateParams.unitId = null;
            }
            this.loadUnitData(data)
        }
        // 岗位
        if (item && item.key === "postCode") {
            this.updateParams.postName = data.map(itm => this.$store.getters.post_map[itm]).join(";");
        }
    }

    public callback(data, type?) {
        if (type) {
            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((itm: any) => itm.id))
        } else if (data && data.value === "subAdd") {
            this.showSubUpdateModel()
        } else if (data && data.value === "subDelete") {
            // 批量删除步骤
            this.doSubDelete(this.selectData.map((itm: any) => itm.index - 1))
        } else if (data && data.value.indexOf("save") >= 0) {
            this.doSave(data.value !== "save")
        } else if (data && data.value === "cancel") {
            this.handleClose()
        }
    }

    public showSubUpdateModel(row?) {
        this.stepUpdateParams = {} as any;
        if (row) {
            this.stepUpdateParams = JSON.parse(JSON.stringify(row));
        }

        this.showSubUpdate = true;
    }

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



    public doSave(goOn?) {
        // 如果是新增步骤
        if (this.showSubUpdate) {
            // 新增
            if (!this.stepUpdateParams.index) {
                this.stepUpdateParams.index = this.updateParams.steps.length + 1;
                this.updateParams.steps.push(this.stepUpdateParams);
            } else {
                this.updateParams.steps.splice(this.updateParams.steps.findIndex(item => item.index === this.stepUpdateParams.index), 1, this.stepUpdateParams)
            }
            this.stepUpdateParams = {} as any;
            this.showSubUpdate = !!goOn;
            return
        }
        // 新增清单
        this.updateParams.safetyFactor = this.updateParams.safetyFactor.join(",");
        this.updateParams.stepNum = this.updateParams.steps.length;
        this.updateParams.postCode = this.updateParams.postCode.join(";")
        this.tableService.addOrUpdate(this.updateParams, !this.updateParams.id).then((res) => {
            this.$message.success(!this.updateParams.id ? "新增成功！" : "编辑成功！");
            this.updateParams = {
                postCode: [],
                safetyFactor: []
            } as any
            this.showUpdate = !!goOn;
            this.getTableData();
        })
    }
    // 重置数据
    public reset() {
        this.params = {
            areaName: "",
            unitName: "",
            name: "",
            pageNum: 1,
            pageSize: 20,
        } as any;
    }

    // 分页数据
    public getTableData() {
        this.tableService.selectByPage(this.params).then(res => {
            this.tableData = res.data as any;
        })
    }

    public showUpdateModel(row?, isRead?) {
        this.isReadonly = !!isRead;
        if (!row) {
            this.updateParams = {
                steps: [], identifyTime: moment().format('YYYY-MM-DD'),
                identifyUserId: this.account.userId,
            } as any;
        } else {
            this.updateParams = JSON.parse(JSON.stringify(row));

            if (!this.updateParams.steps) {
                this.updateParams.steps = [];
            }
            this.updateParams.steps.forEach((item, index) => {
                item.index = index + 1;
            });
            this.currentStepTableData.datas = this.updateParams.steps;
            if (!isRead) {
                this.updateParams.postCode = this.updateParams.postCode.split(";").map(item => +item);
                this.updateParams.safetyFactor = this.updateParams.safetyFactor.split(",").map(item => +item);
            } else {
                this.updateParams.safetyFactor = this.updateParams.safetyFactor.split(",").map(item => +item);
                this.updateParams.safetyFactorName = this.updateParams.safetyFactor.map(item => this.$store.getters.prevention_safe_reason_map[item]).join(",")

            }
        }
        this.buildUpdateForm()
        // 防止选中后影响表单内列表选中
        this.selectData = [];
        this.showUpdate = true
    }

    public handleClose() {
        if (this.showSubUpdate) {
            this.showSubUpdate = false;
            this.stepUpdateParams = {} as any;
            return
        }
        this.showSteptable = false;
        this.isReadonly = false;
        this.showUpdate = false;
        this.updateParams = {} as any;
    }


    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.userId === item.userId);
                if (!find) {
                    (this.$refs.multipleTable as any).toggleRowSelection(item);
                }
            })
        }
    }

    public handleSelectionChange(data) {
        this.selectData = data;
    }
}
</script>
<style lang="scss" scoped src="../../../common.component.scss">
::v-deep {
    .el-dialog__body .common-btn-box {
        justify-content: flex-start !important;
    }
}
</style>
