
<script lang="ts">
import { Component, Watch } from 'vue-property-decorator';
import template from "./device.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 DeviceService from '@/service/device.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 DeviceManagerComponent extends BaseRecordComponent<any> {
    public tableService = new DeviceService();
    public unitService = new UnitService();
    public areaService = new AreaService();

    public params = {
        areaName: "",
        unitName: "",
    } as any;
    public isReadonly = false;
    public currentId = -1;

    public treeData = [] as any;

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

    public subTableColumn = [] as any;
    //检查项目
    public showProject = false;

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

    public updateProParams = {} as any;
    public proIsReadonly = false;
    public showProtable = false;
    public currentProTableData = {
        datas: []
    } as any;


    public showUpdate = false;

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

    public selectData = [];

    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 footerActions = [{
        name: "选择全部",
        value: "selectAll",
        type: "primary"
    }, {
        name: "反向选择",
        value: "reverse"
    }];
    public formOptions: FormOption<BtnOption>[] = [{
        name: "设备名称",
        key: "name",
        type: "text",
    }, {
        name: "设备类别",
        key: "type",
        type: "select",
        datas: this.$store.state.prevention_device_type,
        clearable: true,
    },];


    public updateOptions: FormOption<BtnOption>[] = [] as any;
    public buildUpdateForm() {
        this.updateOptions = [{
            name: "选择区域",
            key: "areaId",
            format: "areaName",
            type: "select",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.areaList
        }, {
            name: "选择单元",
            key: "unitId",
            format: "unitName",
            type: "select",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.unitList
        }, {
            name: "责任部门",
            key: "chargeDeptId",
            format: "chargeDeptName",
            type: "treeSelect",
            require: true,
            width: "calc(50% - 20px)",
            expandLevel: Infinity,
            showError: false,
            datas: this.$store.state.deptTreeList,
        }, {
            name: "责任人",
            key: "chargeUserId",
            format: "chargeUserName",
            type: "select",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.$store.state.userList
        }, {
            name: "设备名称",
            key: "name",
            type: "text",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
        }, {
            name: "设备类型",
            key: "type",
            format: "typeName",
            type: "select",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.$store.state.prevention_device_type
        }, {
            name: "涉及岗位",
            key: "postCode",
            format: "postName",
            multiple: true,
            require: true,
            showError: false,
            type: "select",
            width: "100%",
            clearable: true,
            datas: this.$store.state.postList
        }, {
            name: "安全因素",
            key: "safetyFactor",
            format: 'safetyFactorName',
            require: true,
            type: "select",
            multiple: true,
            clearable: true,
            width: "calc(50% - 20px)",
            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"
        }
        ]
    }

    public updateActions = [] as any;
    public buildActionsForm() {
        this.updateActions = [{
            name: "取消",
            value: "cancel"
        }, {
            name: "保存并继续添加",
            value: "saveAndContinue",
            type: "primary",
            hide: this.updateParams.id
        }, {
            name: "保存",
            value: "save",
            type: "primary"
        }];
    }
    public projectOptions: FormOption<BtnOption>[] = [];
    public subUpdateActions = [] as any;
    public buildSubActionsForm() {
        this.projectOptions = [
            {
                name: "检查项目",
                key: "name",
                type: "textarea",
                require: true,
                width: "100%",
                showError: false,
            },
            {
                name: "检查标准",
                key: "standard",
                type: "textarea",
                require: true,
                width: "100%",
                showError: false,
            },
        ];
        this.subUpdateActions = [{
            name: "取消",
            value: "cancel"
        }, {
            name: "保存并继续添加",
            value: "saveAndContinue",
            type: "primary",
            hide: this.updateProParams.index
        }, {
            name: "保存",
            value: "save",
            type: "primary"
        }];
    }

    @Watch("$store.state.deptList", { immediate: true, deep: true })
    onChanges() {
        this.loadAreaData()
    }


    created() {
        //
    }

    // 加载区域列表
    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() {
        this.tableColumn.push({ name: '区域名称', key: "areaName", width: "200px" });
        this.tableColumn.push({ name: '风险分析单元', key: "unitName", width: "200px" });
        this.tableColumn.push({ name: '设备名称', key: "name", width: "250px", showTip: true, });
        this.tableColumn.push({
            name: '设备类别', key: "type", render: (data) => {
                if (data.type) {
                    return this.$store.getters.prevention_device_type_map[data.type];
                }
            }
        });
        this.tableColumn.push({
            name: '检查项目', key: "itemNum", render: (data) => {
                return "<span class='link'>" + (data.itemNum ? data.itemNum : 0) + "</span>"
            }
        });
        this.tableColumn.push({ name: '责任人', key: "chargeUserName" });
        this.tableColumn.push({ name: '责任部门', key: "chargeDeptName" });
        this.tableColumn.push({ name: '涉及岗位', key: "postName" });

        this.subTableColumn.push({ name: '序号', key: "index", width: "60" });
        this.subTableColumn.push({ name: '检查项目', key: "name" });
        this.subTableColumn.push({ name: '检查标准', key: "standard" });

    }

    public showPros(el, data) {
        const isTarget = el.target.classList.contains("link");
        if (isTarget) {
            this.currentId = data.id;
            this.tableService.selectProjectByPage({ deviceInventoryId: this.currentId }).then((res: any) => {
                if (res.code === 200) {
                    this.showProtable = true;
                    this.currentProTableData.datas = res.data.map((item, index) => {
                        item.index = index + 1;
                        return item
                    })
                }
            })
        }
    }

    public handleClosePro() {
        this.showProtable = false;
    }

    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') {
            this.updateParams.chargeUserName = 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) {
            if (type === 'pageSize' || type === 'pageNum') {
                this.params[type] = data;
            }
            this.getTableData();
            return
        }
        // 查询
        if (data.value === "search") {
            this.getTableData()
            // 重置
        } else if (data.value === "reset") {
            this.reset()
            // 反选
        } else if (data.value === "reverse") {
            this.toggleAll()
            // 全选
        } else if (data.value === "selectAll") {
            this.selectAll()
        } else if (data.value === "delete") {
            this.deleteData(this.selectData)
        } else if (data.value === "add") {
            this.isReadonly = false;
            this.currentId = -1;
            this.updateParams = {
                items: [], identifyUserId: this.account.userId,
                identifyTime: moment().format('YYYY-MM-DD'),
            } as any;
            this.buildActionsForm();
            this.buildUpdateForm();
            this.showUpdate = true
        } else if (data && data.value.indexOf("save") >= 0) {
            this.doSave(data.value !== "save")
        } else if (data && data.value === "cancel") {
            this.handleClose()
        }
    }
    // 重置数据
    public reset() {
        this.params = {
            pageNum: 1,
            pageSize: 20,
        } as any;
        this.getTableData()
    }

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

    public showUpdateModel(row, isReadonly) {
        this.updateParams = { items: [], } as any;
        this.currentId = row.id;
        this.tableService.selectById(this.currentId).then((res: any) => {
            if (isReadonly) {
                this.isReadonly = true;
                this.updateParams = Object.assign({
                    safetyFactorName: res.data.safetyFactor.split(",").map(item => this.$store.getters.prevention_safe_reason_map[item]).join(","),
                    identifyUserName: this.$store.getters.user_map[res.data.identifyUserId],
                    typeName: this.$store.getters.prevention_device_type_map[res.data.type],
                }, res.data)
            } else {
                this.isReadonly = false
                this.updateParams = res.data;
                this.updateParams.safetyFactor = res.data.safetyFactor.split(",").map(item => parseInt(item))
                this.updateParams.postCode = res.data.postCode.split(",").map(item => parseInt(item))
                this.loadUnitData(res.data.areas)
            }
            this.updateParams.items.forEach((item, i) => {
                item.index = i + 1
            })
            this.buildUpdateForm()
            this.buildActionsForm()
            this.showUpdate = true;
        })
    }

    public doSave(goOn?) {
        if ((this.$refs.basicForm as any).vaildParams()) {
            // 新增
            this.updateParams.itemNum = this.updateParams.items.length;
            this.updateParams.postCode = this.updateParams.postCode.join(",")
            this.updateParams.safetyFactor = this.updateParams.safetyFactor.join(",")
            this.tableService.addOrUpdate(this.updateParams, this.updateParams.id ? false : true).then((res) => {
                this.$message.success(!this.updateParams.id ? "新增成功！" : "编辑成功！");
                this.updateParams = {
                    items: [],
                } as any
                this.showUpdate = !!goOn;
                this.getTableData();
            })
        }
    }

    public handleClose() {
        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;
    }

    //检查项目
    public projectCallback(data) {
        if (data && data.value === 'add') {
            this.proIsReadonly = false;
            this.buildSubActionsForm()
            this.showProject = true;

        } else if (data && data.value === 'delete') {
            // 批量删除步骤
            this.deleteProData(this.selectData.map((itm: any) => itm.index - 1))
        }
    }
    //查看 编辑
    public showSubmodal(row, isReadonly) {
        this.proIsReadonly = false;
        this.showProject = true
        if (isReadonly) {
            this.proIsReadonly = true
            this.updateProParams = JSON.parse(JSON.stringify(row));
        } else {
            this.updateProParams = JSON.parse(JSON.stringify(row));
        }
        this.buildSubActionsForm()
    }
    //删除
    public deleteProData(indexs) {
        for (let i = this.updateParams.items.length - 1; i >= 0; i--) {
            if (indexs.includes(i)) {
                this.updateParams.items.splice(i, 1)
            }
        }
        this.updateParams.items.forEach((item, index) => {
            item.index = index + 1;
        });

    }
    public subCallback(data) {
        if (data && data.value.indexOf("save") >= 0) {
            this.doSaveProject(data.value !== "save")
        } else if (data && data.value === "cancel") {
            this.handleProClose()
        }
    }

    public doSaveProject(goOn) {
        // 如果是新增步骤
        if (this.updateProParams) {
            // 新增
            if (!this.updateProParams.index) {
                this.updateProParams.index = this.updateParams.items.length + 1;
                this.updateParams.items.push(this.updateProParams);
            } else {
                this.updateParams.items.splice(this.updateParams.items.findIndex(item => item.index === this.updateProParams.index), 1, this.updateProParams)
            }
            this.updateProParams = {} as any;
            this.showProject = !!goOn;
            return
        }
    }

    public handleProClose() {
        this.showProject = false;
        this.updateProParams = {} as any;
    }
}
</script>
<style lang="scss" scoped src="../../../common.component.scss"></style>
