<template>
    <!-- 排查任务 -->
    <div v-if="visible">
        <FormComponent :options="triUpdateOptions" labelWidth="110px" labelAlign="right" :data.sync="updataParams"
            :isReadonly="isReadonly" :actions="subActions" @actionCallback="callback($event)" :full-btn="true"
            btnPosition="center" @change="change">
            <div class="sub-title">排查任务制定</div>
            <TableComponent :tableData="updataParams.tasks" :tableColumn="tableColumn" @actionCallback="taskAdd($event)"
                :actions="!isReadonly ? tableActions : []" actionPosition="flex-start" :showFooter="false"
                style="margin-bottom: 20px;">
                <el-table ref="multipleTable" :data="updataParams.tasks" tooltip-effect="dark" max-height="500px" border
                    row-key="checked" @selection-change="handleSelectionChange" style="width: 100%">
                    <template v-for="item in tableColumn">
                        <el-table-column v-if="item.render" :show-overflow-tooltip="item.showTip" :label="item.name"
                            :width="item.width" :key="item.key">
                            <div slot-scope="scope" v-html="item.render(scope.row)"></div>
                        </el-table-column>
                        <el-table-column v-else :prop="item.key" :show-overflow-tooltip="item.showTip" :label="item.name"
                            :width="item.width" :key="item.key">
                        </el-table-column>
                    </template>
                    <el-table-column label="操作" fixed="right" width="150">
                        <template slot-scope="scope">
                            <el-button type="text" @click="showTaskModel(scope.row, true)">查看</el-button>
                            <el-button v-if="!isReadonly" type="text" @click="showTaskModel(scope.row)">编辑</el-button>
                            <el-button v-if="!isReadonly" type="text" @click="deleteTask(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

            </TableComponent>
        </FormComponent>

        <el-dialog :close-on-click-modal="false" :title="taskIsReadonly ? '详情' : taskUpdataParams.index ? '编辑' : '新增'"
            :visible.sync="showSubUpdate" width="952px" :before-close="handleCloseTask">
            <FormComponent :options="taskUpdateOptions" :isReadonly="taskIsReadonly" labelWidth="110px" labelAlign="right"
                :data.sync="taskUpdataParams" :actions="subActions" :full-btn="true" btnPosition="center"
                @actionCallback="taskCallback" @change="taskSelectChange">
            </FormComponent>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import FormComponent from 'hbt-common/components/common/form.component.vue';
import { Component, Emit, Prop, PropSync, Vue, Watch } from 'vue-property-decorator';
import BaseRecordComponent from "hbt-common/components/common/baseRecord.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 WorkService from '@/service/work.service';
import UnitService from '@/service/unit.service';
import AreaService from '@/service/area.service';
import SystemService from "hbt-common/service/system.service"
import JobHazardService from '@/service/jobHazard.service';
import ButtonListComponent from "hbt-common/components/common/buttonList.component.vue";
import { L_COLUMN, L_VALUE, S_COLUMN, S_VALUE } from '@/mock/lsRisk';
import { L_LECCOLUMN, L_LECVALUE, E_COLUMN, E_VALUE, C_COLUMN, C_VALUE } from '@/mock/lecRisk';

@Component({
    components: {
        FormComponent,
        TableComponent,
        DrawComponent,
        ButtonListComponent,
    }
})
export default class MeasureComponent extends Vue {

    public systemService = new SystemService();

    public dictData = {
        measuresSort: [],

    } as any;
    //任务排查
    public currentTaskData = { datas: [], deleteIds: [] } as any;

    public tableColumn = [] as any;

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

    public secondTypeItem = [];

    // public updataParams = {} as any;

    //实施措施
    public currentMeasureData = {
        datas: [],
        deleteIds: [],
    } as any;

    public selectData = [];

    public showSubUpdate = false;


    //管控措施
    public measuresSelectData = {} as any;

    public measuresUpdateForm() {
        this.triUpdateOptions = [{
            name: "管控方式",
            key: "controlWay",
            format: "controlWayName",
            type: "select",
            width: "100%",
            require: true,
            datas: this.$store.state.prevention_measure_type
        }, {
            name: "管控措施分类",
            key: "firstType",
            format: "firstTypeName",
            type: "treeSelect",
            require: true,
            expandLevel: Infinity,
            showError: false,
            width: "40%",
            datas: this.dictData.measuresSort
        }, {
            key: "secondType",
            type: "treeSelect",
            format: "secondTypeName",
            require: true,
            expandLevel: Infinity,
            showError: false,
            width: "25%",
            datas: this.secondTypeItem
        }, {
            name:"",
            key: "thirdType",
            type: "text",
            require: true,
            width: "25%",
            showError: false,
        }, {

            name: "措施描述",
            key: "description",
            type: "textarea",
            require: true,
            width: "100%"
        }];
    }

    //排查任务制定
    public taskUpdateOptions: FormOption<BtnOption>[] = [];

    //排查任务
    public taskUpdataParams = {} as any;

    //排查任务类型
    public taskType = [] as any;

    public tasksSelectData = {} as any;

    //包报对应像
    public taskItem = [] as any;

    public taskIsReadonly = false;

    public taskCurrentId = -1;

    public taskUpdateForm() {
        this.taskUpdateOptions = [{
            name: "是否为重大危险源包保责任履职",
            key: "insuranceDutyFlag",
            format: "insuranceDutyFlagName",
            type: "radio",
            width: "100%",
            labelWidth: '210px',
            require: true,
            datas: [
                {
                    name: "否",
                    value: 0
                },
                {
                    name: "是",
                    value: 1
                }
            ]
        }, {
            name: "任务类型",
            key: "taskType",
            format: "taskTypeName",
            type: "treeSelect",
            width: "calc(50% - 20px)",
            require: true,
            datas: this.taskType,
            expandLevel: Infinity,
            disable: !(this.taskUpdataParams.insuranceDutyFlag === 1),
        }, {
            name: "包保任务对应项",
            key: "taskItem",
            format: "taskItemName",
            type: "treeSelect",
            width: "100%",
            require: true,
            expandLevel: Infinity,
            showError: false,
            hide: !(this.taskUpdataParams.insuranceDutyFlag === 1),
            datas: this.taskItem
        }, {
            name: "隐患排查任务",
            key: "name",
            type: "textarea",
            width: "100%",
            require: true,
        }, {
            name: "执行岗位",
            key: "executePostCode",
            format: "executePostName",
            type: "select",
            width: "calc(50% - 20px)",
            require: true,
            datas: this.$store.state.postList,
        },
        {
            name: "责任人",
            key: "chargeUserId",
            format: "chargeUserName",
            type: "select",
            width: "calc(50% - 20px)",
            require: true,
            datas: this.$store.state.userList,
        }, {
            name: "排查周期 每隔",
            key: "reviewCycleValue",
            type: "number",
            width: "calc(50% - 20px)",
            require: true,
            // labelWidth:"130px"
        }, {
            key: "reviewCycleUnit",
            type: "select",
            require: true,
            format: 'reviewCycleValueName',
            datas: this.$store.state.prevention_cycle_unit,
            width: "calc(30% - 20px)",
        }, {
            name: "1次",
            key: "times",
            type: 'null',
            width: "30px",
            labelWidth: "50px"
        }, {
            name: "工作开始时间",
            key: "startTime",
            type: "time",
            width: "calc(50% - 20px)",
            require: true,
            hide: !(this.taskUpdataParams.reviewCycleUnit === 7),
        }, {
            name: "工作结束时间",
            key: "endTime",
            type: "time",
            width: "calc(50% - 20px)",
            require: true,
            hide: !(this.taskUpdataParams.reviewCycleUnit === 7),
        }]
    }

    public subActions = [{
        name: "取消",
        value: "cancel"
    }, {
        name: "保存并继续添加",
        value: "saveAndContinue",
        type: "primary"
    }, {
        name: "保存",
        value: "save",
        type: "primary"
    }];
    public tableActions = [{
        name: "添加",
        value: "fourSubAdd",
        icon: "el-icon-plus",
        type: "primary"
    }];

    @Prop()
    public isReadonly: boolean;

    @PropSync("show", {
        required: true,
        default: true
    })
    public visible: boolean;

    @PropSync("data", {
        required: true,
    })
    public updataParams!: any;
    @Watch("data", { immediate: true, deep: true })
    onParamsValueChange() {
        this.dictData.measuresSort = this.$store.state.prevention_measures_sort.map((item) => {
            this.measuresSelectData[item.value] = this.treeSelectData(item.children)
            return {
                label: item.name,
                id: item.value,
            }
        })
        this.secondTypeItem = this.measuresSelectData[this.updataParams.firstType]
        // if (this.updataParams.tasks && this.updataParams.tasks.length > 0) {
        //     this.updataParams.tasks.forEach((item, index) => {
        //         item.index = index + 1
        //         return item
        //     })
        // }
        this.measuresUpdateForm()
        this.taskUpdateForm()
    }

    @PropSync("tabledata", {
        required: true,
    })
    public measureData!: any;

    created() {

        this.buildTable()
    }


    public buildTable() {
        // 排查任务制定
        this.tableColumn.push({ name: '序号', key: "index", width: "80px" });
        this.tableColumn.push({ name: "任务名称", key: "name" })
        this.tableColumn.push({ name: "执行岗位", key: "executePostName" })
        this.tableColumn.push({ name: "执行人", key: "chargeUserName" })
        this.tableColumn.push({ name: "执行周期", key: "reviewCycleValue" })
        this.tableColumn.push({
            name: "单位", key: "reviewCycleUnit", render: (data) => {
                return this.$store.getters.prevention_cycle_unit_map[data.reviewCycleUnit]
            }
        })
    }
    public change(data, item) {
        //措施类型
        if (item && item.key === 'controlWay') {
            this.updataParams.controlWayName = this.$store.getters.prevention_measure_type_map[data]
        }
        //措施一
        if (item && item.key === "firstType") {
            this.updataParams.firstTypeName = this.selectName(this.dictData.measuresSort, data)
            this.secondTypeItem = this.measuresSelectData[data]
        }
        //措施二
        if (item && item.key === 'secondType') {
            this.updataParams.secondTypeName = this.selectName(this.secondTypeItem, data)
        }
        this.measuresUpdateForm()
    }

    public selectName(selectGroup, data) {
        if (selectGroup && selectGroup.length > 0) {
            const map = {};
            selectGroup.forEach((item: any) => {
                if (item.value) {
                    map[item.value] = item.name
                } else if (item.id) {
                    map[item.id] = item.label
                }

            })
            return map[data]
        }
    }

    public treeSelectData(data) {
        return data.map((item) => {
            return {
                label: item.dictLabel,
                id: isNaN(+item.dictValue) ? item.dictValue : +item.dictValue,
            }
        })

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

    //排查任务
    public showTaskModel(row, isReadonly) {
        this.taskType = this.taskItemSelect()
        if (isReadonly) {
            this.taskIsReadonly = true
            this.taskUpdataParams = JSON.parse(JSON.stringify(row))
            if (row.insuranceDutyFlag === 0) {
                this.taskUpdataParams.taskType = 0
                this.taskUpdataParams.insuranceDutyFlagName = '否'
                this.taskUpdataParams.taskTypeName = '日常任务'
            } else if (row.insuranceDutyFlag === 1) {
                this.taskType = this.taskType.filter(item => item.id !== 0)
                this.taskUpdataParams.insuranceDutyFlagName = "是"
                this.taskItem = this.tasksSelectData[this.taskUpdataParams.taskType]
            }
            this.taskUpdataParams.taskTypeName = this.$store.getters.prevention_task_type_map[row.taskType]
            this.taskUpdataParams.reviewCycleValueName = this.$store.getters.prevention_cycle_unit_map[row.reviewCycleUnit]
            if (this.taskUpdataParams.taskType && this.taskUpdataParams.taskItem) {
                const taskItemName = {} as any;
                this.tasksSelectData[row.taskType].map((item) => {
                    taskItemName[item.id] = item.label
                })
                this.taskUpdataParams.taskItemName = taskItemName[this.taskUpdataParams.taskItem]
            }
            this.taskCurrentId = 0
        } else if (!isReadonly) {
            this.taskIsReadonly = false
            this.taskUpdataParams = JSON.parse(JSON.stringify(row))
            this.taskCurrentId = 0
            if (row.insuranceDutyFlag === 0) {
                this.taskUpdataParams.taskType = 0
                this.taskUpdataParams.insuranceDutyFlagName = '否'
                this.taskUpdataParams.taskTypeName = '日常任务'
            } else if (row.insuranceDutyFlag === 1) {
                this.taskType = this.taskType.filter(item => item.id !== 0)
                this.taskUpdataParams.insuranceDutyFlagName = "是"
                this.taskItem = this.tasksSelectData[this.taskUpdataParams.taskType]
            }
            this.taskUpdataParams.executePostCode = parseInt(row.executePostCode)
        }
        this.showSubUpdate = true
        this.taskUpdateForm()
    }

    //排查任务 --- 包保对应项
    public taskItemSelect() {
        return this.$store.state.prevention_task_type.map((item) => {
            this.tasksSelectData[item.value] = this.treeSelectData(item.children)
            return {
                label: item.name,
                id: item.value,
            }
        })
    }

    public handleCloseTask(goOn?) {
        this.showSubUpdate = false;
        this.taskIsReadonly = false;
        this.taskCurrentId = -1;
        this.taskUpdataParams = {} as any;
    }

    public taskCallback(data) {
        if (data && data.value === 'cancel') {
            this.showSubUpdate = false
        } else if (data && data.value.indexOf("save") >= 0) {
            this.doTaskSave(data.value !== "save")
        }
    }

    //排查任务保存
    public doTaskSave(goOn?) {
        if (!this.taskUpdataParams.index) {
            if (!this.updataParams.tasks) {
                this.updataParams.tasks = []
            }
            this.taskUpdataParams.index = this.updataParams.tasks.length + 1;
            this.updataParams.tasks.push(this.taskUpdataParams);
        } else {
            this.updataParams.tasks.splice(this.updataParams.tasks.findIndex(item => item.index === this.taskUpdataParams.index), 1, this.taskUpdataParams)
        }

        this.updataParams.tasks.forEach((item, i) => {
            item.index = i + 1
        })
        this.taskUpdataParams = {} as any;
        this.showSubUpdate = !!goOn

    }

    public taskAdd() {
        this.showSubUpdate = true
    }

    public deleteTask(row) {
        this.$confirm('确认删除所选数据', '确认数据', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            this.updataParams.tasks.splice(this.updataParams.tasks.findIndex(item => item.index === row.index), 1)
            if (row.id) {
                if (!this.updataParams.deleteIds) {
                    this.updataParams.deleteIds = []
                }
                this.updataParams.deleteIds.push(row.id)
            }
            this.updataParams.tasks.forEach((item, i) => {
                item.index = i + 1
            })
        }).catch(() => {
            //
        });
    }

    //排查任务 -- 下拉选择
    public taskSelectChange(data, item) {

        if (data !== null && data !== undefined) {
            if (item && item.key === 'insuranceDutyFlag') {
                this.taskType = this.taskItemSelect()
                if (data === 0) {
                    this.taskUpdataParams.taskType = 0
                    this.taskUpdataParams.insuranceDutyFlagName = '否'
                    this.taskUpdataParams.taskTypeName = '日常任务'
                } else if (data === 1) {
                    this.taskType = this.taskType.filter(item => item.id !== 0)
                    this.taskUpdataParams.taskType = null
                    this.taskUpdataParams.insuranceDutyFlagName = "是"
                }
            }

            if (item && item.key === "taskType") {
                this.taskItem = this.tasksSelectData[data]
            }
            // 岗位
            if (item && item.key === "executePostCode") {
                this.taskUpdataParams.executePostName = this.$store.getters.post_map[data];
            }
            // 执行人
            if (item && item.key === "chargeUserId") {
                this.taskUpdataParams.chargeUserName = this.$store.getters.user_map[data];
            }
            //任务类型
            if (item && item.key === 'taskType') {
                const map = {};
                this.taskType.forEach((item: any) => {
                    map[item.value] = item.name
                })
                this.taskUpdataParams.taskTypeName = map[data]
            }
            //任务类型
            if (item && item.key === 'taskItem') {
                const map = {};
                this.taskItem.forEach((item: any) => {
                    map[item.value] = item.name
                })
                this.taskUpdataParams.taskItemName = map[data]
            }
            this.taskUpdateForm()
        }
    }

    public callback(data) {
        if (data && data.value === 'cancel') {
            this.visible = false;
            this.updataParams = {} as any;
        } else if (data && data.value.indexOf("save") >= 0) {
            this.doMeasureSave(data.value !== "save")
        }
    }

    public doMeasureSave(goOn) {
        if (!this.updataParams.tasks) {
            this.updataParams.tasks = []
        }
        if (!this.updataParams.index) {
            this.updataParams.index = this.measureData.measures.length + 1;
            this.updataParams.tasksNum = this.updataParams.tasks.length
            this.measureData.measures.push(this.updataParams);
        } else {
            this.updataParams.tasksNum = this.updataParams.tasks.length
            this.measureData.measures.splice(this.measureData.measures.findIndex(item => item.index === this.updataParams.index), 1, this.updataParams)
        }
        this.updataParams = {} as any;
        this.visible = !!goOn;
    }
    //分析法 
    @Emit("actionCallback")
    actionCallback(data) {
        //Emit false
    }

}
</script>
<style lang="scss" scoped  src="../views/common.component.scss"></style>
<style lang="scss" scoped>
::v-deep .vue-treeselect__label {
    white-space: break-spaces;
}
</style>
