
<script lang="ts">
import { Component, Watch } from 'vue-property-decorator';
import template from './common.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 riskCardService from "@/service/riskCard.service";
import FormOption from "hbt-common/models/formOptions";
import BtnOption from "hbt-common/models/btnOptions";
import UnitService from '@/service/unit.service';
import AreaService from '@/service/area.service';

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

    public params = {
        areaName: null,
        riskLevel: null,
        postCode: null
    } as any;

    public showProtable = false;

    public tableColumn = [] as any;

    public subUpdateParams = {} as any;

    public updateParams = {} as any;

    public areaList = [] as any;

    public unitList = [] as any;


    public selectData = [];

    public subIsReadonly = false;

    public isReadonly = false;

    public fileList = [] as any;

    public showFile = false;
    public currentUrl = null;

    public subShowUpdate = false;

    public showUpdate = false;

    public setpsOptions = [] as any;
    
    public showFileModal = false;

    public showFileList = [] as any;

    public labelWidth='130px'

    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: "areaName",
        type: "text",
    }, {
        name: "风险等级",
        key: "riskLevel",
        type: "select",
        datas: this.$store.state.prevention_risk_level
    }, {
        name: "岗位名称",
        type: "select",
        key: "postCode",
        datas: this.$store.state.postList,
        width: "270px",
    }];

    public subActions = [{
        name: "取消",
        value: "cancel"
    }];


    public updateActions = [] as any;

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

    public updateStepsOptions: FormOption<BtnOption>[] = [] as any;

    public subUpdateOptions: FormOption<BtnOption>[] = [] as any;

    public buildUpdateForm() {
        this.subUpdateOptions = [{
            name: "风险告知卡编号",
            type: "text",
            key: "number",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            disable: true,
            labelWidth:"130px"
        },
        {
            name: "区域名称",
            type: "select",
            key: "areaId",
            format: "areaName",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.areaList
        },
        {
            name: "单元名称",
            type: "select",
            key: "unitId",
            format: "unitName",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.unitList
        },
        {
            name: "岗位名称",
            type: "select",
            key: "postCode",
            format: "postName",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.$store.state.postList
        },
        {
            name: "危险有害因素",
            type: "textarea",
            key: "harmfulFactors",
            require: true,
            width: "100%",
            showError: false,
        },
        {
            name: "事故风险与后果",
            type: "textarea",
            key: "riskResult",
            require: true,
            width: "100%",
            showError: false,
            labelWidth:'130px'
        },
        {
            name: "风险等级",
            type: "select",
            key: "riskLevel",
            format: "riskLevelName",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.$store.state.prevention_risk_level
        },
        {
            name: "安全标志",
            type: "select",
            key: "safetySign",
            format: "safetySignName",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.$store.state.prevention_security_identifier,
            filterable: true,
            multiple: true,
        },
        {
            name: "风险管控措施",
            type: "textarea",
            key: "riskControlMeasure",
            require: true,
            width: "100%",
            showError: false,
        },
        {
            name: "应急处置措施",
            type: "textarea",
            key: "emergencyHandleMeasure",
            require: true,
            width: "100%",
            showError: false,
        },
        {
            name: "附件",
            key: "resourceId",
            ref: "file",
            type: "upload",
            width: "100%",
            showError: false,
            onSucess: this.onSuccess,
            onMove: this.onRemove,
            onPreview: this.onPreview,
            autoUpload: true,
            accept: "image/png, image/jpeg,.doc,.docx,.xls,.xlsx,.pdf",
            listType: "text",
            tip: this.subIsReadonly ? "" : "请上传.pdf,.png,.jpg,.doc.docx,.xls,.xlsx格式文件",
            fileList: this.fileList,
            btn: [{
                name: "上传附件",
                value: "upload",
                hide: this.subIsReadonly,
                size: "small",
                type: "primary"
            }]
        },
        ];
        this.updateActions = [{
            name: "取消",
            value: "cancel"
        }, {
            name: "保存并继续添加",
            value: "saveAndContinue",
            type: "primary",
            hide: this.subUpdateParams.id
        }, {
            name: "保存",
            value: "save",
            type: "primary"
        }];
    }

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

    created() {
    }


    // 加载区域列表
    public loadAreaData() {
        this.unitList = [];
        this.areaService.selectByPage({ pageSize: 1000 }).then((res: any) => {
            this.areaList = res.data.datas.map(item => {
                return {
                    name: item.name,
                    value: item.id,
                    analRiskLevel: item.analRiskLevel ? item.analRiskLevel : null,
                }
            });
            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 changes(data, item) {
        if (item && item.key === "areaId") {
            if (this.subUpdateParams.unitId) {
                this.subUpdateParams.unitId = null;
            }
            const areaData = this.areaList.find((itm: any) => itm.value === data) as any;
            this.subUpdateParams.areaName = areaData.name
            this.loadUnitData(data)
        }

        //单元
        if (item && item.key === 'unitId') {
            const unitData = this.unitList.find((itm: any) => itm.value === data) as any;
            this.subUpdateParams.unitName = unitData.name;
        }
    }

    public buildTable() {
        this.tableColumn.push({ name: '区域名称', key: "areaName", });
        this.tableColumn.push({ name: '单元名称', key: "unitName", });
        this.tableColumn.push({ name: '岗位名称', key: "postName", });
        this.tableColumn.push({ name: '主要危险有害因素', key: "harmfulFactors", });
        this.tableColumn.push({
            name: '风险等级', key: "riskLevel",width:"150px", render: (data) => {
                if (data.riskLevel) {
                    return "<span class='color_level_" + data.riskLevel + "'>" + (data.riskLevel ? (this.$store.getters.prevention_risk_level_map[data.riskLevel]) : '') + "</span>"
                }
            }
        });
        this.tableColumn.push({ name: '事故风险与后果', key: "riskResult", });
        this.tableColumn.push({
            name: '安全警示标志', key: "safetySign", render: (data) => {
                if (data.safetySign) {
                    return data.safetySign.split(",").map(item => this.$store.getters.prevention_security_identifier_map[item]).join(",")
                }
            }
        });
    }

    public callback(data, type) {
        if (type) {
            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.map((item: any) => item.id))
        } else if (data.value === 'add') {
            this.subUpdateParams = {} as any;
            this.subIsReadonly = false;
            this.fileList = [] as any;
            this.getNumber()
        }
    }

    //获取编号
    public getNumber() {
        this.tableService.getNumber({}).then((res: any) => {
            if (res.code === 200) {
                this.subUpdateParams.number = res.data
            } else {
                this.$message.error(res.msg)
            }
            this.buildUpdateForm()
            if (this.subShowUpdate === false) {
                this.subShowUpdate = true
            }
        })
    }

    // 分页数据
    public getTableData() {
        this.tableService.selectByPage(this.params).then(res => {
            this.tableData = res.data as any;
        })
    }
    // 重置数据
    public reset() {
        this.params = {
            pageNum: 1,
            pageSize: 20,
        } as any;
    }

    public showUpdateModel(id) {
        this.subShowUpdate = true
    }

    public handleClose() {
        this.subShowUpdate = 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 onSuccess(res, file, fileList) {
        if (res.code === 200) {
            this.fileList.push({
                name: res.data.originalName,
                url: res.data.url,
                type: res.data.type,
                id: res.data.id
            })
        } else {
            this.$message.error(res.msg);
        }

    }

    public onRemove(file, fileList) {
        this.fileList.splice(this.fileList.findIndex(item => item.id === file.response.data.id), 1)
    }

    public onPreview(file) {
        if (file.type.indexOf("png") >= 0 || file.type.indexOf("jp") >= 0) {
            this.currentUrl = file.url;
            this.showFile = true;
        } else {
            window.open(file.url, "_blank")
        }
    }

    public subCallback(data) {
        // 
    }

    public triCallback(data) {
        if (data.value === "cancel") {
            this.subShowUpdate = false
        } else if (data && data.value.indexOf("save") >= 0) {
            this.doSave(data.value !== "save")
        }
    }

    public doSave(goOn?) {
        // 新增清单
        if (this.fileList.length > 0) {
            let resourceId = this.fileList.map((item) => {
                return item.id
            })
            let resourceName = this.fileList.map((item) => {
                return item.name
            })
            this.subUpdateParams.resourceId = resourceId.join(",")
            this.subUpdateParams.resourceName = resourceName.join(",")
        }
        this.subUpdateParams.postName = this.$store.getters.post_map[this.subUpdateParams.postCode]
        this.subUpdateParams.safetySign = this.subUpdateParams.safetySign.join(",")
        this.tableService.addOrUpdate(this.subUpdateParams, this.subUpdateParams.id ? false : true).then((res) => {
            this.$message.success(!this.subUpdateParams.id ? "新增成功！" : "编辑成功！");
            this.subUpdateParams = {} as any
            this.subShowUpdate = !!goOn;
            this.getTableData();

            if (goOn === true) {
                this.getNumber()
            }
        })
    }

    public showModal(row, isReadonly) {
        if (isReadonly) {
            this.subIsReadonly = true

        } else {
            this.subIsReadonly = false
        }

        this.tableService.getListDetail({ id: row.id }).then((res: any) => {
            if (res.code === 200) {
                this.subUpdateParams = Object.assign({
                    riskLevelName: this.$store.getters.prevention_risk_level_map[res.data.riskLevel],
                    safetySignName: res.data.safetySign.split(",").map(item => this.$store.getters.prevention_security_identifier_map[item]).join(",")
                }, res.data)
                if (res.data.resourceId) {
                    this.tableService.getFileUrls({ ids: res.data.resourceId.split(",") }).then((files: any) => {
                        this.fileList = files.data.map(item => {
                            return {
                                name: item.originalName,
                                url: item.url,
                                type: item.type,
                                id: item.id
                            }
                        })
                        this.subUpdateParams.resourceId = ''
                        this.buildUpdateForm()
                    })
                }

                if (!isReadonly) {
                    this.subUpdateParams.safetySign = this.stringChangeArray(res.data.safetySign)
                }

                this.buildUpdateForm()
                this.subShowUpdate = true
            } else {
                this.$message.error(res.msg);
            }

        })
    }


    //字符串转数组
    public stringChangeArray(data) {
        if (data) {
            return data.split(",").map((item) => parseInt(item))
        }
    }
}
</script>
<style lang="scss" scoped src="../common.component.scss"></style>