
<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 emergencyCardService from "@/service/emergencyCard.service";
import FormOption from "hbt-common/models/formOptions";
import BtnOption from "hbt-common/models/btnOptions";
import AreaService from '@/service/area.service';
import TinyEditor from "@/components/tinyEditor.component.vue";
import { Base64 } from 'js-base64';
import ButtonListComponent from "hbt-common/components/common/buttonList.component.vue"

@Component({
    template,
    components: {
        FormComponent,
        TableComponent,
        TinyEditor,
        ButtonListComponent
    },
})
export default class EmergencyCard extends BaseRecordComponent<any> {
    public tableService = new emergencyCardService();
    public areaService = new AreaService();

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

    public showProtable = false;

    public tableColumn = [] as any;

    public showUpdate = false;

    public updateParams = {} as any;

    public selectData = [];

    public isReadonly = false;

    public subIsReadonly = false;

    public areaList = [] as any;

    public subUpdateParams = { index: null } as any;

    public fileList = [] as any;
    public photoList = [] as any;

    public fileList2 = [] as any;
    public photoList2 = [] as any;

    public showFile = false;
    public currentUrl = null;

    public subShowUpdate = false;


    public showFileModal = false;

    public showFileList = [] as any;

    public labelWidth = null;

    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: "accidentRisk",
        type: "text",
    }];

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




    public updateActions = [] as any;

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

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

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

    public buildUpdateForm() {
        this.updateOptions = [{
            name: "处置卡编号",
            type: "text",
            key: "number",
            require: true,
            width: "calc(50% - 20px)",
            disable: true,
            showError: false,
        },
        {
            name: "处置卡名称",
            type: "text",
            key: "name",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
        },
        {
            name: "区域名称",
            type: "select",
            key: "areaId",
            format: "areaName",
            require: true,
            width: "calc(50% - 20px)",
            datas: this.areaList,
            showError: false,
        },
        {
            name: "岗位名称",
            type: "select",
            key: "postCode",
            format: "postName",
            require: true,
            width: "calc(50% - 20px)",
            datas: this.$store.state.postList,
            showError: false,
        },
        {
            name: "发生场所",
            type: "text",
            key: "occurPlace",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
        },
        {
            name: "事故风险",
            type: "text",
            key: "accidentRisk",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
        },
        {
            name: "工艺说明",
            type: "text",
            key: "technologyDescription",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
        },
        {
            name: "事故特征",
            type: "text",
            key: "accidentFeature",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
        },
        {
            name: "危害描述",
            type: "text",
            key: "harmDescription",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
        },
        {
            name: "注意事项",
            type: "text",
            key: "attention",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
        },
        {
            name: "处置步骤说明",
            type: "textarea",
            key: "content",
            require: true,
            width: "100%",
            showError: false,
        },
        ];

        this.updateStepsOptions = [{
            name: "主要负责人",
            type: "select",
            key: "chargeUserId",
            format: "chargeUserName",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.$store.state.userList,
        },
        {
            name: "联系方式",
            type: "text",
            key: "chargeUserPhone",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            rules: [
                { pattern: /^1[3|5|7|8|9]\d{9}$/, message: '请输入正确的号码格式', }
            ]
        },
        {
            name: "消防联络方式",
            type: "text",
            key: "fireControlPhone",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            // rules: [
            //     { pattern: /^1[3|5|7|8|9]\d{9}$/, message: '请输入正确的号码格式', }
            // ]
        },
        {
            name: "应急联络方式",
            type: "text",
            key: "emergencyPhone",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            // rules: [
            //     { pattern: /^1[3|5|7|8|9]\d{9}$/, message: '请输入正确的号码格式', }
            // ]
        },
        {
            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.isReadonly ? "" : "请上传.pdf,.png,.jpg,.doc.docx,.xls,.xlsx格式文件",
            fileList: this.fileList,
            btn: [{
                name: "上传附件",
                value: "upload",
                hide: this.isReadonly,
                size: "small",
                type: "primary"
            }]
        },
        ];

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

    public setpsOptions = [] as any;

    public buildStepForm() {
        this.setpsOptions = [{
            key: 1,
            index: 1,
            name: '',
            description: ''
        }]
    }




    @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,
                    analRiskLevel: item.analRiskLevel ? item.analRiskLevel : null,
                }
            });
            this.buildUpdateForm()
        })
    }

    public buildTable() {
        this.tableColumn.push({ name: '处置卡名称', key: "name" });
        this.tableColumn.push({ name: '区域名称', key: "areaName" });
        this.tableColumn.push({ name: '岗位', key: "postName" });
        this.tableColumn.push({ name: '发生场所', key: "occurPlace" });
        this.tableColumn.push({ name: '事故特征', key: "accidentFeature" });
        this.tableColumn.push({ name: '事故风险', key: "accidentRisk" });
        this.tableColumn.push({ name: '危害描述', key: "harmDescription" });
    }

    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.updateParams = {} as any;
            this.setpsOptions = [] as any;
            this.isReadonly = false;
            //清除附件缓存数据
            this.clearFileListMethod()
            this.getNumber()
        }
    }

    //获取编号
    public getNumber() {
        this.tableService.getNumber({}).then((res: any) => {
            if (res.code === 200) {
                this.updateParams.number = res.data
            } else {
                this.$message.error(res.msg)
            }
            this.buildUpdateForm()
            if (this.showUpdate === false) {
                this.showUpdate = true
                this.setpsOptions = [{
                    key: 1,
                    index: 1,
                    name: '',
                    description: ''
                },] as any;
            }
        })
    }

    // 分页数据
    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;
        this.getTableData()
    }

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

    public handleClose() {
        this.showUpdate = false;
        //清除附件缓存数据
        this.clearFileListMethod()
    }


    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) {
        if (data.value === "cancel") {
            this.showUpdate = false;
            //清除附件缓存数据
            this.clearFileListMethod()
        } else if (data && data.value.indexOf("save") >= 0) {
            this.doSave(data.value !== "save")
        }
    }


    public triCallback(data) {
        //
    }

    public deleteSteps(data) {

        this.setpsOptions.splice(this.setpsOptions.findIndex(item => item.key === data.key), 1)
        this.setpsOptions.forEach((item, index) => {
            item.key = Math.random().toString().split(".")[1]
            item.index = index + 1
        })
    }

    public addSteps(data) {
        let stepsParam = {
            name: '',
            description: ''
        } as any;

        stepsParam.key = Math.random().toString().split(".")[1];
        stepsParam.index = this.setpsOptions.length + 1;
        this.setpsOptions.push(stepsParam)
    }


    public doSave(goOn?) {
        let vaildParams = true
        if (!((this.$refs.basicForm as any).vaildParams())) {
            vaildParams = false
        }
        if (!((this.$refs.stepForm as any).vaildParams())) {
            vaildParams = false
        }
        if (vaildParams === false) {
            return
        }
        // 新增清单
        if (this.fileList.length > 0) {
            let resourceId = this.fileList.map((item) => {
                return item.id
            })
            let resourceName = this.fileList.map((item) => {
                return item.name
            })
            this.updateParams.resourceId = resourceId.join(",")
            this.updateParams.resourceName = resourceName.join(",")
        }

        this.setpsOptions.forEach((item, index) => {
            const editor = (this.$refs.editor as any)[index].getContent()
            item.description = Base64.encode(editor)
        })
        this.updateParams.postName = this.$store.getters.post_map[this.updateParams.postCode]
        this.updateParams.chargeUserName = this.$store.getters.user_map[this.updateParams.chargeUserId]
        this.updateParams.step = JSON.stringify(this.setpsOptions)
        this.tableService.addOrUpdate(this.updateParams, this.updateParams.id ? false : true).then((res) => {
            this.$message.success(!this.updateParams.id ? "新增成功！" : "编辑成功！");
            this.updateParams = {} as any
            this.showUpdate = !!goOn;
            this.getTableData();
            //清除附件缓存数据
            this.clearFileListMethod()
            if (goOn === true) {
                this.getNumber()
            }
        })

    }

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

        } else {
            this.isReadonly = false
        }
        this.setpsOptions = [] as any;

        this.tableService.getListDetail({ id: row.id }).then((res: any) => {
            if (res.code === 200) {
                this.updateParams = res.data
                this.setpsOptions = JSON.parse(res.data.step);
                this.setpsOptions.forEach((item) => {
                    item.description = Base64.decode(item.description)

                })
                this.updateParams.postCode = parseInt(this.updateParams.postCode)
                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.updateParams.resourceId = ''
                        this.buildUpdateForm()
                    })
                }

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

        })
    }


    public changes(data, item) {
        //
    }

    /**
     * 清除附件数据
     */
    public clearFileListMethod() {
        this.fileList = [];
        const option = this.updateStepsOptions.find(item => item.key === "resourceId") as any;
        option.fileList = [];
    }


}
</script>
<style lang="scss" scoped src="../common.component.scss"></style>
<style  lang="scss" scoped >
::v-deep {
    .step-form {
        max-height: 780px;
        overflow: hidden;
        overflow-y: auto;

        .el-form-item__content {
            margin-left: 0px !important;

            .form-group-name {
                width: calc(50% - 20px);
                display: inline-flex;
                margin-right: 20px;
                margin-bottom: 20px;


                .form-label {
                    width: 110px;
                    text-align: right;
                    white-space: nowrap;
                    flex: none;
                    height: 40px;
                    align-self: flex-start;
                    line-height: 40px;
                    margin-right: 15px
                }

                .form-content {
                    position: relative;
                    flex: 1;
                    display: flex;
                    align-items: center;
                }


            }

            .icon {
                width: calc(50% - 20px);

            }

            .el-icon-error {
                color: #F56C6C;
                float: right;
                margin-right: 20px;
                font-size: 28px;
            }

            .el-icon-error:hover {
                color: #fd8080;
                font-size: 28px;
            }

            .el-icon-circle-plus {
                color: #409EFF;
                float: right;
                margin-right: 5px;
                font-size: 28px;
            }

            .el-icon-circle-plus:hover {
                color: #66b1ff;
                font-size: 28px;
            }

            .form-group-step {
                width: calc(100% - 20px);
                display: inline-flex;
                margin-right: 20px;
                margin-bottom: 20px;

                .form-label {
                    width: 110px;
                    text-align: right;
                    white-space: nowrap;
                    flex: none;
                    height: 40px;
                    align-self: flex-start;
                    line-height: 40px;
                    margin-right: 15px
                }

                .form-content {
                    position: relative;
                    flex: 1;
                    display: flex;
                    align-items: center;

                    .el-textarea {
                        position: relative;
                        vertical-align: bottom;
                        font-size: 14px;
                    }
                }

                // .tox-tinymce {
                //     border-radius: 4px;
                // }

                // .tox-statusbar__text-container {
                //     display: none;
                // }

                // .tox .tox-statusbar {
                //     border-top: 0;
                // }

                // .tox .tox-toolbar-overlord>.tox-toolbar,
                // .tox .tox-toolbar-overlord>.tox-toolbar__overflow,
                // .tox .tox-toolbar-overlord>.tox-toolbar__primary {
                //     //
                // }
            }
        }


        .form-group {
            display: inline-flex;
            margin-right: 20px;
            margin-bottom: 20px;
            width: calc(100% - 20px);

            .form-label {
                width: 110px;
                text-align: right;
                white-space: nowrap;
                flex: none;
                height: 40px;
                align-self: flex-start;
                line-height: 40px;
                margin-right: 15px
            }

            .form-content {
                position: relative;
                flex: 1;
                display: flex;
                align-items: center
            }
        }

    }

}
</style>