
<script lang="ts">
import { Component } from 'vue-property-decorator';
import template from "./rules.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 TableService from '@/service/table.service';
import UnitService from '@/service/unit.service';
import AreaService from '@/service/area.service';
import RuleService from '@/service/rule.service';
@Component({
    template,
    components:{
        FormComponent,
        TableComponent,
        DrawComponent,
    },
})
export default class RulesManagerComponent extends BaseRecordComponent<any> {
    public tableService = new TableService();
    public unitService = new UnitService()
    public areaService = new AreaService()

    public ruleService = new RuleService()

    public params = {} as any;

    public isReadonly = false;

    public subIsReadonly = false;
    public isManager = true;

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

    public formActions = [{
        name:"查询",
        value:"search",
        icon:"el-icon-search",
        type:"primary"
    }];

    public tableActions = [{
        name:"添加",
        value:"add",
        icon:"el-icon-plus",
        type:"primary"
    },{
        name:"批量删除",
        value:"delete",
        plain:true,
        icon:"el-icon-delete",
        type:"danger"
    }];
    public updateTableActions = [{
        name:"添加",
        value:"subAdd",
        plain:true,
        icon:"el-icon-plus",
        type:"success"
    },{
        name:"批量删除",
        value:"subDelete",
        plain:true,
        icon:"el-icon-delete",
        type:"danger"
    },{
        name:"批量添加",
        value:"subMutilAdd",
        icon:"el-icon-plus",
        type:"primary"
    }];
    public footerActions = [{
        name:"选择全部",
        value:"selectAll",
        type:"primary"
    },{
        name:"反向选择",
        value:"reverse"
    }];
    public formOptions:FormOption<BtnOption>[] = [{
        name:"检查表名称",
        key:"name",
        type:"text"
    }];
    public mutilAddOptions:FormOption<BtnOption>[] = [];

    public showUpdate = false;
    public currentId = -1;
    public updateParams = {}  as any;
    public subUpdateParams = {}  as any;
    public updateOptions:FormOption<BtnOption>[] = [];
    public updateTableData = {datas:[]};
    public updateTableColumn = []  as any;
    public showSubUpdate = false;
    public showSubMutilUpdate = false;
    public ruleParams = {
        pageSize:10,
        pageNum:1
    }

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

    public subUpdateOptions = [{
        name:"检查项目",
        type:"text",
        require:true,
        showError:false,
        width:"100%",
        key:"name",
    },{
        name:"检查内容",
        type:"textarea",
        require:true,
        width:"100%",
        showError:false,
        key:"content",
    },{
        name:"检查依据",
        type:"textarea",
        require:true,
        width:"100%",
        showError:false,
        key:"reason",
    }]

    public subUpdateActions = [{
        name:"取消",
        value:"cancelSub"
    },{
        name:"确定",
        value:"saveSub",
        type:"primary"
    }];

    public selectData = [];
    

    created(){
        this.loadAreaData();
        this.loadRuleTable();
    }

    public loadRuleTable(num?,type?){
        if(type && num){
            this.ruleParams[type] = num
        }else{
            this.ruleParams = {
                pageSize:10,
                pageNum:1
            }
        }
        this.ruleService.selectByPage(this.ruleParams).then((res:any)=>{
            this.updateTableData = res.data;
            this.updateTableData.datas.forEach((item:any,index)=>{
                item.index = index+1;
            })
        })
    }

    public buildUpdateForm(){

        this.mutilAddOptions = [{
            name:"检查项目",
            key:"name",
            type:"text"
        },{
            name:"类型",
            key:"type",
            clearable:true,
            type:"select",
            datas:this.$store.state.prevention_dangrous_type
        }]
        this.updateOptions = [{
            name:"检查表编号",
            key:"number",
            type:"text",
            width:"calc(50% - 20px)",
            require:true,
            disable:true,
        },{
            name:"检查表名称",
            key:"name",
            type:"text",
            width:"calc(50% - 20px)",
            require:true,
            showError:false,
        },{
            name:"适用区域",
            key:"areas",
            type:"select",
            multiple:true,
            width:"calc(50% - 20px)",
            require:true,
            showError:false,
            datas:this.areaList
        },{
            name:"适用单元",
            key:"units",
            type:"select",
            multiple:true,
            width:"calc(50% - 20px)",
            require:true,
            showError:false,
            datas:this.unitList
        },{
            name:"适用对象",
            key:"targets",
            type:"select",
            multiple:true,
            width:"calc(50% - 20px)",
            require:true,
            showError:false,
            datas:this.$store.state.analControlList,
        },{
            name:"适用部门",
            key:"depts",
            multiple:true,
            type:"select",
            width:"calc(50% - 20px)",
            require:true,
            showError:false,
            datas:this.$store.state.deptList
        },{
            name:"适用类型",
            key:"types",
            type:"select",
            width:"calc(50% - 20px)",
            require:true,
            multiple:true,
            showError:false,
            datas:this.$store.state.prevention_dangrous_type
        }]
    }

     // 加载区域列表
     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.loadUnitData()
        })
    }
    // 加载单元列表
    public loadUnitData(ids?){
        this.unitService.getListByIds({areaIds:ids},false).then((res:any)=>{
            this.unitList = res.data.map(item=>{
                return {
                    name:item.name,
                    value:item.id
                }
            });
            this.buildUpdateForm()
        })
    }

    public getNumber(){
        this.tableService.getNumber().then(res=>{
            this.updateParams.number = res.data
        })
    }

    public buildTable(){
        this.tableColumn = [];
        this.tableColumn.push({name:'检查表名称',key:"name"});
        this.tableColumn.push({name:'区域名称',key:"areas"});
        this.tableColumn.push({name:'单元名称',key:"units"});
        this.tableColumn.push({name:'对象名称',key:"targets"});
        this.tableColumn.push({name:'适用部门',key:"depts"});
        this.tableColumn.push({name:'适用类型',key:"types",filters:this.$store.state.prevention_dangrous_type.map(item=>{
            return {
                text:item.name,
                value:item.name,
            }
        }),filterMethod:(data,row)=>{
            return row.types.indexOf(data)>=0;
        }});
        this.tableColumn.push({name:'编制人',key:"createName"});
        this.tableColumn.push({name:'编制时间',key:"createTime"});
        this.updateTableColumn = [];

        this.updateTableColumn.push({name:'序号',key:"index",width:"60px"});
        this.updateTableColumn.push({name:'检查项目',key:"name",showTip:true});
        this.updateTableColumn.push({name:'检查内容',key:"content",showTip:true});
        this.updateTableColumn.push({name:'检查依据',key:"reason",showTip:true});
        if(this.showSubMutilUpdate){
            this.updateTableColumn.push({name:'检查类型',key:"reason",render:(data)=>{
                return this.$store.getters.prevention_dangrous_type_map[data.type]
            }});
        }
    }

    public change(data,item){
        
        // 区域
        if(item && item.key==="areas"){
            if(this.updateParams.units.length){
                this.updateParams.units = [];
            }
            this.loadUnitData(data)
        }
    }

    public callback(data,type?){
        if(type){
            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((item:any)=>item.id))
        }else if(data && data.value.indexOf("save")>=0){
            this.doSave(data.value!=="save")
        }else if(data && data.value === "cancel"){
            this.handleClose()
        }
    }

    public subChange(data,item){
        //
    }

    public subCallback(data){
        if(data && data.value==="subAdd"){
            this.showSubUpdateModel()
        }else if(data && data.value.indexOf("save")>=0){
            this.doSubSave(data.value!=="save")
        }else if(data && data.value==="cancel"){
            this.handleClose()
        }else if(data && data.value==="subDelete"){
            this.doSubDelete(this.selectData.map((item:any)=>item.index -1))
        }else if(data && data.value==="subMutilAdd"){
            this.showSubMutilUpdate = true;
            this.buildTable()
            this.clearSelect()
        }
    }

    public doMutilAdd(){
        this.selectData.forEach((item:any)=>{
            if(!this.updateParams.tableItems.find(itm=>itm.id===item.id)){
                const data = JSON.parse(JSON.stringify(item))
                delete data.id;
                this.updateParams.tableItems.push(data)
            }
        })

        this.updateParams.tableItems.forEach((item,i)=>{
            item.index = i+1
        })
        this.clearSelect()
        this.showSubMutilUpdate=false;
        this.buildTable();
    }

    public cancelMutilAdd(){
        this.clearSelect();
        this.ruleParams = {
            pageNum:1,
            pageSize:10,
        }
        this.showSubMutilUpdate=false;
        this.buildTable();

    }

    public clearSelect(){
        (this.$refs.multipleTable as any).clearSelection();
        this.selectData = [];
    }
    // 重置数据
    public reset(){
        this.params = {
            name:"",
            pageNum:1,
            pageSize:20,
        } as any;

        this.ruleParams = {
            pageNum:1,
            pageSize:10,
        }
    }

    public showSubUpdateModel(row?,isRead?){
        this.subUpdateParams = {} as any;
        this.subIsReadonly = !!isRead;
        if(row){
            this.subUpdateParams = JSON.parse(JSON.stringify(row))
        }
        this.showSubUpdate = true;
    }



    public showUpdateModel(row?,isRead?){
        this.updateParams = {number:null,tableItems:[]} as any;
        this.isReadonly = !!isRead;
        this.clearSelect()

        this.buildUpdateForm();
        if(!row){
            this.currentId = -1;
            this.getNumber();
            this.showUpdate = true;
        }else{
            this.currentId = row.id;
            this.tableService.selectById(this.currentId,true).then((res:any)=>{
                if(isRead){
                    this.updateParams = Object.assign(res.data,row)
                }else{
                    this.updateParams = res.data;
                    this.loadUnitData(res.data.areas)
                }

                this.updateParams.tableItems.forEach((item,i)=>{
                    item.index = i+1
                })
                this.showUpdate = true;
            })
        }
    }
    public doSubSave(goOn?){
        if(!this.subUpdateParams.index){
            this.subUpdateParams.index = this.updateParams.tableItems.length+1;
            this.updateParams.tableItems.push(this.subUpdateParams);
        }else{
            this.updateParams.tableItems.splice(this.updateParams.tableItems.findIndex(item=>item.index ===this.subUpdateParams.index),1,this.subUpdateParams)
        }

        this.updateParams.tableItems.forEach((item,i)=>{
            item.index = i+1
        })
        this.subUpdateParams = {} as any;
        this.showSubUpdate = !!goOn
    }

    public  doSubDelete(indexs){
        for(let i = this.updateParams.tableItems.length-1;i>=0;i--){
            if(indexs.includes(i)){
                this.updateParams.tableItems.splice(i,1)
            }
        }

        this.updateParams.tableItems.forEach((item,i)=>{
            item.index = i+1
        })
        this.clearSelect()
    }

    public doSave(goOn?){
        this.updateParams.depts = this.updateParams.depts.map(item=>{
            return {
                id:item,
                name:this.$store.getters.dept_map[item]
            }
        })

        this.updateParams.targets = this.updateParams.targets.map(item=>{
            return {
                id:item,
                name:this.$store.getters.prevention_anal_control_map[item]
            }
        })
        this.tableService.addOrUpdate(this.updateParams,this.currentId===-1).then(res=>{
            this.$message.success(this.currentId===-1?"新增成功！":"编辑成功");
            this.getTableData();
            this.showUpdate = !!goOn;
            this.updateParams = {areas:[],depts:[],units:[],types:[],targets:[],number:null} as any;
        }).catch(()=>{
            this.updateParams.depts = this.updateParams.depts.map(item=>item.id)

            this.updateParams.targets = this.updateParams.targets.map(item=>item.id)
        })
    }

    public handleClose(){
        if(this.showSubMutilUpdate){
            this.showSubMutilUpdate = false;
            this.buildTable();
            return
        }
        if(this.showSubUpdate){
            this.showSubUpdate = false;
            return
        }
        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;
    }
}
</script>
<style lang="scss" scoped src="../../common.component.scss"></style>
