<template>
    <el-dialog title="添加问题" v-model="dialogFormVisible" :append-to-body="true" width="90%" @close="closeDialog" :close-on-click-modal="false" class="add_problem_dialog">
        <el-form :model="form" :rules="rules" ref="form" label-width="140px" class="problem_form">
            <el-form-item label="选择问题">
                <el-select v-model="keyword" filterable popper-class="problem_select" style="width: 88%" placeholder="请选择" @change="changeSelect">
                    <el-option
                    v-for="item in problemList"
                    :key="item.id"
                    :label="item.pblmsDesc"
                    :value="item.id">
                    </el-option>
                </el-select>
                <span class="add_new_problem" @click="addNewProblem" v-if="!isFujian">添加其它问题</span>
            </el-form-item>
            <el-card class="box-card" body-style="{ padding-right: 20px;padding-top: 16px;padding-bottom: 2px; padding-left: 2px; }">
                <div class="text item">
                    <p class="item_title">
                        <i class="el-icon-caret-right"></i>
                        <span>对应《清单》内容</span>
                        <span style="font-size: 12px;color: red;">(该部分内容可根据实际情况调整法规条款和法规内容)</span>
                    </p>
                    <el-form-item label="问题描述">
                        <el-input v-model="attachInfo.pblmsDesc" readonly type="textarea" :autosize="{ minRows: 5}" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="法规条款">
                        <el-input v-model="attachInfo.relativeLaw"  type="textarea" :autosize="{ minRows: 5}" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="法规内容">
                        <el-input v-model="attachInfo.lawContent"  type="textarea" :autosize="{ minRows: 5}" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="备注">
                        <el-input v-model="attachInfo.note" readonly type="textarea" :autosize="{ minRows: 1}" autocomplete="off"></el-input>
                    </el-form-item>
                </div>
            </el-card>
            <el-card class="box-card" body-style="{ padding-right: 20px;padding-top: 16px;padding-bottom: 2px; padding-left: 2px; }">
                <div class="text item">
                    <p class="item_title">
                        <i class="el-icon-caret-right"></i>
                        <span>责任主体</span>
                        <span class="el-icon-circle-plus" title="添加单位" @click="addUnit"></span>
                    </p>
                    <div v-for="(unit,index) in unitArray" :key="index">
                        <el-form-item label="单位性质" style="display: inline-block">
                            <el-select v-model="unit.subId" placeholder="请选择" @change="natureChange(val,index)">
                                <el-option
                                v-for="item in objSubjectList"
                                :key="item.id"
                                :label="item.subName"
                                :value="item.id">
                                </el-option>
                            </el-select>
                            <span class="el-icon-remove" title="删除单位" v-if="index != 0" @click="removeUnit(index)"></span>
                        </el-form-item>
                        <el-form-item label="单位名称" style="display: inline-block">
                            <el-select v-model="unit.unitNm" popper-class="problem_select" @change="unitSelect" placeholder="请选择">
                                <el-option
                                v-for="item in unitNameList"
                                :key="item.id"
                                :label="item.sctnName ? `${item.sysNm}(${item.sctnName})` : item.sysNm"
                                :value="item.sysNm">
                                </el-option>
                            </el-select>
                            <!-- <el-input v-model="unit.unitNm" autocomplete="off"></el-input> -->
                        </el-form-item>
                    </div>
                </div>
            </el-card>
            <el-card class="box-card" body-style="{ padding-right: 20px;padding-top: 16px;padding-bottom: 2px; padding-left: 2px; }">
                <div class="text item">
                    <el-form-item label="排序序号" prop="sn">
                        <el-input v-model="form.sn" autocomplete="off" style="width: 210px"></el-input>
                    </el-form-item>
                    <el-form-item label="问题名称">
                        <el-input v-model="form.pblmNm" placeholder="请输入问题名称" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="问题阐述">
                        <el-input v-model="form.pblmDesc" placeholder="请输入问题详细描述" type="textarea" :autosize="{ minRows: 7}" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="问题严重性" style="display: inline-block" prop="pblmPasi">
                      <el-select v-if="selectShow && !isGd && !isSc && !isSd" v-model="form.pblmPasi" placeholder="请选择" @change="changeRules">
                        <el-option v-for="item in cateObjList" :key="item.cate" :label="item.desc"
                                   :value="item.cate">
                        </el-option>
                      </el-select>

                      <el-select  v-if="isGd || isSc || isSd" v-model="form.pblmPasi" placeholder="请选择">
                        <el-option  label="一般" value="0"></el-option>
                        <el-option  label="较重" value="1"></el-option>
                        <el-option  label="严重" value="2"></el-option>
                      </el-select>
                      <!-- <el-input v-if="inputShow" v-model="form.pblmPasi" :placeholder="inputText">

                      </el-input> -->
                      <span v-if="inputShow && !isGd && !isSc && !isSd">{{inputText}}</span>
                    </el-form-item>
<!--                    <el-form-item label="问题严重性" style="display: inline-block" prop="pblmPasi">-->
<!--                        <el-select v-if="selectShow" v-model="form.pblmPasi" placeholder="请选择">-->
<!--                            <el-option-->
<!--                            v-for="item in cateObjList"-->
<!--                            :key="item.cate"-->
<!--                            :label="item.desc"-->
<!--                            :value="item.cate">-->
<!--                            </el-option>-->
<!--                        </el-select>-->
<!--                        &lt;!&ndash; <el-input v-if="inputShow" v-model="form.pblmPasi" :placeholder="inputText">-->

<!--                        </el-input> &ndash;&gt;-->
<!--                        <span v-if="inputShow">{{inputText}}</span>-->
<!--                    </el-form-item>-->
                    <el-form-item label="问题是否典型" style="display: inline-block">
                            <el-radio v-model="form.ifCasePblm" label="1">是</el-radio>
                            <el-radio v-model="form.ifCasePblm" label="0">否</el-radio>
                    </el-form-item>
                    <el-form-item label="问题分类" prop="pblmTypeDesc">
                        <!-- pblmQlttvCd -->
                        <el-select v-model="form.pblmTypeDesc" filterable popper-class="problem_select" style="width: 88%" placeholder="请选择">
                            <el-option
                            v-for="(item,index) in problemDxList"
                            :key="index"
                            :label="item"
                            :value="item">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="主要原因分析" prop="pblmReason">
                        <el-input v-model="form.pblmReason" type="textarea" :autosize="{ minRows: 7}" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="整改意见及建议" prop="pblmSggtn">
                        <el-input v-model="form.pblmSggtn" type="textarea" :autosize="{ minRows: 7}" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="稽察组长复核意见">
                        <el-input v-model="form.spclRvwOptn" type="textarea" :autosize="{ minRows: 7}" autocomplete="off"></el-input>
                    </el-form-item>
                  <el-form-item label="新增问题修改理由">
                    <el-input v-model="form.pblmRevision" type="textarea" :autosize="{ minRows: 7}" autocomplete="off"></el-input>
                  </el-form-item>
                    <el-form-item label="取证材料">
                        <span style="display: block;text-align: center;color:red;">佐证照片建议上传2至6的偶数张</span>
                        <upload
                            ref="uploadFile"
                            :url="`/pdcApi/file/insert?bizId=`"
                            @uploadOver="removeNewSupervision"
                        ></upload>
                    </el-form-item>
                </div>
            </el-card>
        </el-form>
        <add-new-problem-com v-if="innerVisible" :titleType="'添加'" :listType="listType" @dialogClose="closeInnerDialog"></add-new-problem-com>
        <template #footer class="dialog-footer">
            <el-button @click="closeDialog">取 消</el-button>
            <el-button type="primary" @click="submitProblem">保 存</el-button>
        </template>
    </el-dialog>
</template>
<script>
import {getSelectProblemList,getProblemNatureApi,submitProblemApi1,getUnitNameListApi,getProblemDxListApi} from '@/api/InspectionReport.js'
import addNewProblemCom from './addInspectionProblem.vue'
export default {
    props: ['currentNodeId','objId','listType','pertype','stepId','isRevision'],
    data() {
        var checkSn = (rule, value, callback) => {
            if (value && value<0) {
                return callback(new Error('序号应大于0'));
            }
            setTimeout(() => {
                if (value && (!(/(^[1-9]\d*$)/.test(value)) || value<0)) {
                    callback(new Error('请输入大于0的正整数'));
                } else {
                    callback();
                }
            }, 500);
        };
    //这里存放数据
        return {
            inputShow:false,
            selectShow:true,
            inputText:'',
            dialogFormVisible: true,
            keyword: '',
            problemList: [],
            form:{
                pblmDesc: '',
                pblmNm: '',
                pblmQlttvCd: '',
                pblmPasi: '',
                ifCasePblm: '',
                pblmReason: '',
                pblmSggtn: '',
                spclRvwOptn: '',
                gwComFileList: [],
                pblmSubjectList:{
                    unitNm:'',
                    subId:''
                },
                subjectIds: '',
                subjectNames: '',
                objType: '8',
                objId: '',
                rgstrId: '',//登记表id
                pblmstdId: '',//稽察问题标准库id
                listType: '', //六个专业的类型123456
                sn: '',
              pblmRevision: '',
              pblmRevisionProof: '',
            },
            attachInfo: {
                pblmsDesc: '',
                relativeLaw: '',
                lawContent: '',
                note: ''
            },
            newForm: {
                pblmsDesc: '',
                relativeLaw: '',
                lawContent: '',
                note: ''
            },
            problemInfo: {},
            gwComFileList: [],
            cateObjList:[],//严重程度列表
            objSubjectList: [], //单位性质列表
            unitNameList: [],  //单位名称列表
            unitArray: [
                {
                    unitNm:'',
                    subId:''
                }
            ],
            innerVisible: false,
            rules: {
                sn: [
                    { validator: checkSn, trigger: 'blur' }
                ],
                pblmTypeDesc: [
                    { required: true, message: '请选择问题类别', trigger: 'change'}
                ],
                pblmPasi: [
                { required: true, message: '请选择问题严重性', trigger: 'change'}
                ],
                pblmReason: [
                    { required: true, message: '请输入主要原因分析', trigger: 'change' }
                ],
                pblmSggtn: [
                    { required: true, message: '请输入意见及建议', trigger: 'change' }
                ]
            },
            problemDxList: [],  //问题分类列表
            relCode: '',  //问题标准序号
        };
    },
    components:{
        upload: resolve => {
            require(["../../../widgets/uploadFileWithPic.vue"], resolve);
        },
        addNewProblemCom
    },
    //监听属性 类似于data概念
    computed: {
        persId() {
            return localStorage.getItem("userid") ? localStorage.getItem("userid") : "1098101939614724096";
        },
        isGd(){
            if(localStorage.getItem('currentRlcode').substring(0,2)=="44"){
                return true;
            }else{
                return false;
            }
        },
        isSc(){
            if(localStorage.getItem('currentRlcode').substring(0,2)=="51"){
                return true;
            }else{
                return false;
            }
        },
        isFujian(){
            if(localStorage.getItem('currentRlcode').substring(0,2)=='35'){
                return true;
            }else{
                return false;
            }
        },
        isSd(){
            if(localStorage.getItem('currentRlcode').substring(0,2)=="37"){
                return true;
            }else{
                return false;
            }
        },
        isHb(){
            if(localStorage.getItem('currentRlcode').substring(0,2)=="42"){
                return true;
            }else{
                return false;
            }
        }
    },
    //监控data中的数据变化
    watch: {
    },
    //方法集合
    methods: {
        changeRules(){
            if(this.isHb){
                if(this.form.pblmPasi=="0"){
                    this.rules["pblmReason"][0].required = false;
                    this.rules["pblmSggtn"][0].required = false;
                }else{
                    this.rules["pblmReason"][0].required = true;
                    this.rules["pblmSggtn"][0].required = true;
                }
            }
        },
        getProblemList(){
            getSelectProblemList(this.keyword,this.listType).then(res=>{
                if(res.success){
                    this.problemList = res.data.list
                }else{
                    this.$message.error(res.message)
                }
                this.loading = false
            }).catch(err=>{
                this.$message.error(err)
            })
        },
        changeSelect(val){
            var _self = this;
            getProblemNatureApi(val).then(res=>{
                if(res.success){
                    this.problemInfo = res.data
                    this.attachInfo.pblmsDesc = this.problemInfo.pblmsDesc
                    this.attachInfo.relativeLaw = this.problemInfo.relativeLaw
                    this.attachInfo.lawContent = this.problemInfo.lawContent
                    this.attachInfo.note = this.problemInfo.note
                    this.objSubjectList = this.problemInfo.objSubjectList
                    this.cateObjList = this.problemInfo.cateObjList
                    this.form.pblmNm = this.attachInfo.pblmsDesc   //发现问题项的内容默认为问题描述内容  可更改
                    this.relCode = this.problemInfo.class2   //获取问题分类列表需要的问题标准序号
                    if(this.cateObjList.length == 1){
                        this.inputShow = true;
                        this.selectShow = false;
                        this.form.pblmPasi = this.cateObjList[0].cate;
                        this.inputText = this.cateObjList[0].desc;
                    }else{
                        this.inputShow = false;
                        this.selectShow = true;
                    }
                    // 切换问题标准时问题严重性赋值问题
                    this.cateObjList.forEach(ele=>{
                        if(this.form.pblmPasi && this.form.pblmPasi != ele.cate){
                            this.form.pblmPasi = ''
                        }
                    })
                    this.problemDxList = []
                    if(this.problemInfo.pblmTypeDesc){
                        this.problemDxList.push(this.problemInfo.pblmTypeDesc)
                    }
                    if(this.problemInfo.pblmTypeDesc2){
                        this.problemDxList.push(this.problemInfo.pblmTypeDesc2)
                    }
                    // this.getProblemDxList()   //不通过这个方法获取问题定性列表了，直接在上面取pblmTypeDesc和pblmTypeDesc2的值
                }else{
                    this.$message.error(res.message)
                }
            }).catch(err=>{
                this.$message.error(err)
            })
        },
        getProblemDxList(){
            getProblemDxListApi(this.relCode,this.listType).then(res=>{
                if(res.success){
                    this.problemDxList = res.data
                }else{
                    this.$message.error(res.message)
                }
            }).catch(err=>{
                this.$message.error(err)
            })
        },
        addUnit(){
            this.unitArray.push({unitNm:'',unitId: '',subId:'',subName:''})
        },
        removeUnit(index){
            this.unitArray.splice(index,1)
        },
        submitProblem(){
            this.$refs['form'].validate((valid) => {
                if(valid){
                    if(!this.keyword){
                        this.$message.warning('请选择问题')
                        return
                    }
                    // this.problemDxList.forEach((ele,index)=>{
                    //     if(ele.code == this.form.pblmQlttvCd){
                    //         this.form['pblmQlttvNm'] = ele.name
                    //     }
                    // })
                    let unitNames = []
                    let subIds = []
                    this.unitArray = this.uniArr(this.unitArray);
                    this.unitArray.forEach((ele, index) => {
                        unitNames.push(ele.unitNm)
                        subIds.push(ele.subId)
                    })
                    unitNames = unitNames.filter(function (s) {
                        return s && s.trim();
                    });
                    subIds = subIds.filter(function (s) {
                        return s && s.trim();
                    });
                    if((unitNames.length!=subIds.length) && unitNames.length!=0 && subIds.length!=0){
                        this.$message.warning("对应的单位性质或单位名称其中一个不能为空");
                        return false;
                    }
                    //问题严重性为一般和较重时修改问题是否典型隐藏 默认为否
                    // if(this.form.pblmPasi != '2' || this.form.ifCasePblm == ''){
                    //     this.form.ifCasePblm = '0'
                    // }
                    this.form.relativeLaw = this.attachInfo.relativeLaw
                    this.form.lawContent = this.attachInfo.lawContent
                    this.form.subjectNames = unitNames.join(',')
                    this.form.subjectIds = subIds.join(',')
                    this.form.pblmSubjectList = this.unitArray
                    this.form.persId = this.persId
                    this.form.rgstrId = this.currentNodeId
                    this.form.objId = this.objId
                    this.form.listType = this.listType
                    this.form.pblmstdId = this.keyword
                    this.form.stepId  = this.stepId
                    if(this.form.sn == ''){
                        this.form.sn = 0
                    }
                    if(this.form.pblmReason.length >= 500){
                        this.$message.warning('主要原因分析需字数小于500字！');
                        return;
                    }
                    if(this.form.pblmSggtn.length >= 1000){
                        this.$message.warning('整改意见及建议字数需小于1000字！');
                        return;
                    }
                    if(this.form.spclRvwOptn.length >= 500){
                        this.$message.warning('稽察组长意见字数需小于500字！');
                        return;
                    }
                   if(this.form.pblmRevision.length >= 500){
                    this.$message.warning('问题修改理由字数需小于500字！');
                     return;
                   }
                    submitProblemApi1(this.form).then(res=>{
                        if(res.success){
                            this.$message.success('添加成功')
                            this.gwComFileList = [];
                            if (this.$refs.uploadFile.submitUpload(res.data.id)) {
                                this.removeNewSupervision();
                            }
                        }else{
                            this.$message.error(res.message)
                        }
                    }).catch(err=>{
                        this.$message.error(err)
                    })
                } else {
                    return false;
                }
            })
        },
        uniArr(tempArr) {
            var newTempArr = [];
            if(tempArr && tempArr.length>0){
                tempArr.forEach((item,index)=>{
                    if(item.unitNm || item.subId){
                        newTempArr.push(item);
                    }
                })
                for (let i = 0; i < newTempArr.length; i++) {
                    for (let j = i + 1; j < newTempArr.length; j++) {
                        if ((newTempArr[i].unitNm == newTempArr[j].unitNm) && (newTempArr[i].subId == newTempArr[j].subId)) {
                            newTempArr.splice(j, 1);
                            j--;
                        };
                    };
                };
                return newTempArr;
            }else{
                return [];
            }
        },
        addNewProblem(){
            this.innerVisible = true
        },
        getUnitNameList(index){
            let paramsObj = {
                rgstrId: this.currentNodeId,
                sysType: this.unitArray[index].subId
            }
            this.unitArray[index].unitNm = ''  //单位性质切换的时候清空单位名称
            getUnitNameListApi(paramsObj).then(res=>{
                if(res.success){
                    this.unitNameList = res.data
                }else{
                    this.$message.error(res.message)
                }
            }).catch(err=>{
                this.$message.error(err)
            })
        },
        unitSelect(){
            let _this = this
            this.unitArray.forEach((ele,index)=>{
                _this.unitNameList.forEach(element=>{
                    if(ele.unitNm == element.sysNm){
                        this.unitArray[index].unitId = element.id
                    }
                })
            })
        },
        natureChange(val,index){
            this.getUnitNameList(index)
            let _this = this
            this.unitArray.forEach((ele,index)=>{
                _this.objSubjectList.forEach(element=>{
                    if(ele.subId == element.id){
                        this.unitArray[index].subName = element.subName
                    }
                })
            })
        },
        closeDialog(){
            this.$emit('dialogClose')
        },
        removeNewSupervision(arg) {
            if (arg) {
                var args = this.gwComFileList.concat(arg);
            }
            this.gwComFileList = [];
            this.$emit('dialogClose')
        },
        // 文件上传
        submitUpload() {
            this.$refs.upload.submit();
        },
        //监听内容dialog关闭时执行
        closeInnerDialog(){
            this.innerVisible = false
            this.getProblemList()
        }
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {

    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {
        this.getProblemList()
    }
}
</script>
<style >
    .add_problem_dialog{
        .el-dialog{
            margin-top: 6vh !important;
            margin-bottom: 20px;
        }
        .el-dialog__body{
            font-size: 16px;
            color: #333;
        }
        .problem_form{
            width: 98%;
            margin: 0 auto;
            padding: 16px;
            height: calc(100vh - 270px);
            overflow: auto;
            .item_title{
                margin-top:10px;
                margin-bottom: 20px;
                span:nth-of-type(1){
                    width:120px;
                    padding-left: 5px
                }
            }
            .hrs{
                display: inline-block;
                width: calc(100% - 40px);
                margin-left:10px;
                height: 1px;
                vertical-align: middle;
                background-color: #ddd;
            }
            .el-icon-circle-plus,.el-icon-remove{
                margin-left: 10px;
                color: #009fff;
                cursor: pointer;
            }
            .el-icon-remove{
                color: red;
            }
            .box-card{
                margin-bottom: 6px;
            }
            .el-form-item__label{
                font-size: 16px;
                color: #333;
            }
        }
        .el-button--mini{
            font-size: 14px;
        }
        .el-input--mini{
            font-size: 14px;
        }
        .el-textarea.is-disabled .el-textarea__inner{
            color: #666;
        }
    }
    .problem_select .el-select-dropdown__item{
        width: 800px;
    }
    .problem_form{
        .add_new_problem{
            color: #009fff;
            cursor: pointer;
        }
    }
</style>
