
<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: "",
        areaId: '',
        unitId: '',
        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,
        steps: [],
        chargeUserId: null,
    } as any;

    public selectData = [];

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

    public isReadonly = false;


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


    public updateActions = [] as any;
    public updateActionsForm() {
        this.updateActions = [{
            name: "取消",
            value: "cancel"
        }, {
            name: "保存并继续添加",
            value: "saveAndContinue",
            type: "primary",
            hide: this.updateParams.id
        }, {
            name: "保存",
            value: "save",
            type: "primary"
        }];
    }

    public subUpdateActions = [] as any;
    public subUpdateActionsForm() {
        this.subUpdateActions = [{
            name: "取消",
            value: "cancel"
        }, {
            name: "保存并继续添加",
            value: "saveAndContinue",
            type: "primary",
            hide: this.stepUpdateParams.index
        }, {
            name: "保存",
            value: "save",
            type: "primary"
        }];
    }



    public showSubUpdate = false;

    public showSteptable = false;

    public subUpdateOptions: FormOption<BtnOption>[] = [];
    @Watch("$store.state.deptList", { immediate: true, deep: true })
    @Watch("$store.state.userList", { 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,
            clearable: true,
            datas: this.$store.state.postList
        }, {
            name: "安全因素",
            key: "safetyFactor",
            format: "safetyFactorName",
            type: "select",
            multiple: true,
            clearable: 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?, isTree = false) {
        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,
                    deptName: item.chargeDeptName,
                    userId: item.chargeUserId,
                    userName: item.chargeUserName,
                }
            });
            const option = this.updateOptions.find(item => item.key === "unitId") as any;
            option.datas = this.unitList
            if (this.updateParams.unitId && isTree) {
                this.selectUnitMethod(this.updateParams.unitId)
            }
        })
    }
    // 树点击
    public handleNodeClick(data: any) {
        this.params.areaName = "";
        this.params.areaId = "";
        this.params.unitName = "";
        this.params.unitId = "";
        if (data.areaId) {
            this.params.unitName = data.name;
            this.params.unitId = data.id;
            this.params.areaId = data.areaId
        } else {
            this.params.areaName = data.name === "全部" ? "" : data.name;
            this.params.areaId = data.name === "全部" ? "" : data.id;
        }
        this.getTableData()
    }

    public buildTable() {

        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.tableService.getListDetail({ id: data.id }).then((res: any) => {
                this.currentStepTableData.datas = res.data.steps.map((item, index) => {
                    item.index = index + 1;
                    return item
                })
            })


        }
    }

    public changes(data, item) {
        //单元
        if (item && item.key === 'unitId') {
            //选择单元
            this.selectUnitMethod(data);
        }
        // 部门
        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(",");
        }
    }
    /**
     * 选择单元 填写关联数据
     * @param data 单元id
     */
    public selectUnitMethod(data: any) {
        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;
        const option = this.updateOptions.find(item => item.key === "chargeUserId") as any;
        option.showError = false;
    }

    /**
     * 按钮操作函数
     * @param data 
     * @param type 
     */
    public callback(data: any, 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((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 subCallback(data: any, type: any) {
        if (data && data.value.indexOf("save") >= 0) {
            this.doSubSave(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;
        this.subUpdateActionsForm();
        this.buildUpdateForm();
    }

    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;
        });
    }


    /**
     * 保存数据
     * @param goOn 
     */
    public doSave(goOn?) {
        if (this.updateParams.steps.length === 0) {
            this.$message.warning("请您至少添加一条作业步骤！");
            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: [],
                identifyTime: moment().format('YYYY-MM-DD'),
                identifyUserId: this.account.userId,
                steps: []
            } as any
            this.showUpdate = !!goOn;
            this.getTableData();
        })
    }
    /**
     * 保存步骤数据
     */
    public doSubSave(goOn?) {
        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
    }
    // 重置数据
    public reset() {
        this.params = {
            areaName: "",
            unitName: "",
            areaId: '',
            unitId: '',
            name: "",
            pageNum: 1,
            pageSize: 20,
        } as any;
        this.getTableData()
    }

    // 分页数据
    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,
                chargeUserId: null,
            } as any;
            //树点击
            if (this.params.areaId) {
                this.updateParams.areaId = this.params.areaId;
                this.loadUnitData(this.params.areaId, true)
                this.updateParams.unitId = this.params.unitId;
            }
            this.updateActionsForm()
        } else {
            this.tableService.getListDetail({ id: row.id }).then((res) => {
                this.updateParams = JSON.parse(JSON.stringify(res.data));
                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);
                    this.loadUnitData(this.updateParams.areaId)
                } 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.updateParams.identifyUserName = this.$store.getters.user_map[this.updateParams.identifyUserId];
                }
                this.updateActionsForm()
            })

        }


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

    public handleSelectionChange(data) {
        this.selectData = data;
    }

    //添加作业步骤
    public addWorkSteps() {
        this.showSubUpdateModel();
    }

    //删除
    public deleteData(ids: any) {
        if (!ids.length) {
            return
        } else {
            this.$confirm("确认删除所选数据？", "确认数据", {
                type: 'warning'
            }).then(() => {
                this.tableService.deleteByIds(ids).then((res: any) => {
                    if (res.data.type === 0) {
                        this.$message.success("删除成功！");
                        this.getTableData()
                    } else {
                        let title = '';
                        if (res.data.names.length > 3) {
                            title = '“' + res.data.names.slice(0, 3).join('”，“') + '” 等'
                        } else {
                            title = '“' + res.data.names.join('”，“') + '”'
                        }
                        this.$confirm(`${title}作业活动下存在评估数据，请先删除对应数据`, "", {
                            type: 'warning',
                            showConfirmButton: false
                        }).then(() => {
                            //
                        }).catch(() => {
                            //
                        })
                    }
                })
            }).catch(() => {
                //
            })
        }
    }
}
</script>
<style lang="scss" scoped src="../../../common.component.scss"></style>
<style lang="scss" scoped>
::v-deep {

    .el-step__line {
        background-color: #409EFF;
        text-align: center;
    }

    .el-step.is-vertical .el-step__head {
        width: 64px;
        text-align: center;
    }

    .el-step__icon.is-text {
        width: 64px;
        background: #409EFF;
        border-radius: 4px;
        color: #fff;
        border: 0px;
        font-size: 12px;
    }

    .el-step__description {
        padding-right: 20px;
    }

    .el-step.is-vertical .el-step__main {
        padding-left: 16px;
    }

    .el-step.is-vertical .el-step__title {
        font-size: 16px;
        font-weight: 500;
        color: #409EFF;
        padding-bottom: 16px;
        display: flex;
        justify-content: space-between;
    }

    .el-step.is-vertical .el-step__line {
        left: 32px;
        opacity: 0.3;
    }

    .description {


        .el-textarea.is-disabled .el-textarea__inner {
            background: rgba(64, 158, 255, 0.05) !important;
        }

        .el-textarea__inner {
            font-size: 14px !important;
            font-weight: 400 !important;
            color: rgba(0, 0, 0, 0.6) !important;
            background: rgba(64, 158, 255, 0.05) !important;
            border-radius: 4px;
            border-color: #fff !important;
            padding: 16px;
        }


    }

    .basic-content {
        padding: 18px 0px;
        font-size: 14px;
        font-weight: 500;
        color: rgba(0, 0, 0, 0.3);
        display: flex;
        justify-content: flex-start;

        .content-item {
            width: 33%;

            span {
                color: rgba(0, 0, 0, 0.6);
            }
        }
    }

    .end-step {
        .el-step__head.is-wait {
            height: 9px !important;
        }

        .el-step__icon.is-text {
            width: 9px;
            height: 9px;
            background: #C5E1FF;
            border-radius: 50%;
            margin-left: 2px;
            margin-bottom: 6px;

            .el-step__icon-inner {
                display: none;
            }
        }
    }

    .end-title {
        height: 17px;
        font-size: 12px;
        font-weight: 500;
        color: #C5E1FF;
        line-height: 17px;
        padding-left: 22px;
        margin-bottom: 20px;
    }

    .add-steps-btn {
        width: 100%;
        text-align: center;
        height: 40px;
        background: #ECF5FF;
        border-radius: 4px;
        border: 1px solid #409EFF;
        line-height: 40px;
        color: #409EFF;
        cursor: pointer;
        margin: 0px 20px 20px 20px;
    }

    .modify-img {
        background: #409EFF;
        width: 24px;
        height: 24px;
        border-radius: 50%;
        cursor: pointer;
    }

    .delete-img {
        width: 24px;
        height: 24px;
        margin-left: 20px;
        margin-right: 20px;
        cursor: pointer;
    }
}
</style>
