<!--新增信息配置-->
<template>
  <div class="page-container notice-addPage">
    <div class="page-top-title-box">
      <p class="page-top-title-name-p">{{form.detailId?'编辑':'新增'}}</p>
      <p class="page-top-title-out-p" @click="backPage">返回</p>
      <p class="page-top-title-add-p" @click="submitForm">提交</p>
    </div>
    <div class="content-box">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" >
        <el-form-item label="信息名称:" prop="infoName">
          <el-input v-model="form.infoName" maxlength="100" placeholder="请输入名称" style="width:600px;"/>
        </el-form-item>
        <el-form-item label="信息类目:"  prop="brandId" class="form-item">
          <el-select placeholder="请选择类目" v-model="form.brandId" style="width:600px;" @change="categoryClick()">
            <el-option
              v-for="dict in categoryList"
              :key="dict.brandId"
              :label="dict.brandName"
              :value="dict.brandId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="信息类型:">
          <el-input v-model="form.infoType==1?'文字':'图片'"   placeholder="" disabled style="width:600px;"/>
        </el-form-item>
        <el-form-item label="信息内容:" prop="infoContent" v-if="form.infoType==1">
          <el-input type="textarea" v-model="form.infoContent"  maxlength="200" placeholder="请输入内容" style="width:600px;"/>
        </el-form-item>
        <el-form-item label="信息内容:" prop="infoContent" v-if="form.infoType==2">
          <el-upload
            class="certificate-avatar-uploader"
            :action="uploadImgUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :headers="headers"
            :before-upload="beforeAvatarUpload">
            <div style="display: flex;">
              <img v-if="form.infoContent" :src="form.infoContent" style="width: 80px;height: 80px;margin-right: 10px">
              <i v-if="!form.infoContent" class="el-icon-plus avatar-uploader-icon"></i>
            </div>
          </el-upload>
        </el-form-item>
        <P v-if="form.infoType==2" style="margin-left: 120px">图片最大上传630*78，建议尺寸58*78</P>
        <el-form-item label="危险源:">
          <p class="danger-tip">实验室危险源满足以下分类配置，会在信息牌中自动显示此安全信息。</p>
        </el-form-item>
        <div class="danger-table">
          <el-table class="table-box" v-loading="loading" border :data="form.listHazardModel"  ref="table-box">
            <el-table-column label="序号" type="index" align="center" width="50"/>
            <el-table-column label="危险源主分类"  align="left" prop="hazardName" show-overflow-tooltip/>
            <el-table-column label="危险源子分类"  align="left" prop="hazardCodeName" show-overflow-tooltip/>
            <el-table-column label="操作" width="120" align="left">
              <template slot-scope="scope">
                <div class="table-button-box">
                  <p class="table-button-null"></p>
                  <p class="table-button-p"
                   @click="delHazard(scope.row)"
                  >删除</p>
                  <p class="table-button-null"></p>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="danger-add" @click="dangerAdd">+ 新增危险源</div>
      </el-form>
    </div>
    <el-dialog title="新增危险源分类" :visible.sync="dialogVisible" width="970px" append-to-body>
      <div class="classify-name"><i>*</i>选择危险源分类:</div>
      <div class="classify">
        <div class="classify-li" v-for="(item,index) in conditionList">
          <div class="classify-li-l">{{item.hazardName}}</div>
          <div class="classify-li-r">
            <p><el-checkbox v-model="item.checkAll" @change="handleCheckAllChange($event,item)">{{item.allName}}</el-checkbox></p>
            <p>
              <el-checkbox-group v-model="item.checkedCities" @change="handleCheckedCitiesChange($event,item)">
                <el-checkbox v-for="item2 in item.dictItemModels" :label="item2.label" :key="item2.value">{{item2.label}}</el-checkbox>
              </el-checkbox-group>
            </p>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer dialog-footer-box">
        <p class="dialog-footer-button-null"></p>
        <p class="dialog-footer-button-info" @click="cancel">取消</p>
        <p class="dialog-footer-button-primary" @click="conditionSubmitForm">保存</p>
        <p class="dialog-footer-button-null"></p>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  laboratoryBrandDetailAdd, laboratoryBrandDetailGetDetailHazardConfig,
  laboratoryBrandDetailUpdate,
  laboratoryInfoBrandList
} from '@/api/integratedManagement'
  import { getToken } from '@/utils/auth'
  export default {
    name: 'addPage',
    props:{
      propsData:{},
    },
    data(){
      return{
        uploadImgUrl: this.uploadUrl(), // 上传的图片服务器地址
        loading:false,
        headers: {
          Authorization: getToken()
        },
        tabsList:[],
        categoryList:[],
        infoType:null,
        form: {
          brandId:'',
          infoName:'',
          infoType:'',
          infoContent:'',
          isCollective:'',
          listHazardModel:[],
        },
        dataList:[],
        dialogVisible:false,
        conditionList:[],

        // 表单校验
        rules: {
          infoName: [
            { required: true, message: "请输入名称", trigger: "blur" },
          ],
          brandId: [
            { required: true, message: "请选择类目", trigger: "blur" },
          ],
          infoContent: [
            { required: true, message: "请添加信息内容", trigger: "blur" },
          ],
        }
      }
    },
    created(){
      this.form = this.propsData;

    },
    mounted(){
      this.getCategoryList();
      this.laboratoryBrandDetailGetDetailHazardConfig();
    },
    methods:{
      dangerAdd(){
        this.dialogVisible=true;
      },
      //全选按钮
      handleCheckAllChange(val,item) {
        let name=[];
        for (let i=0;i<item.dictItemModels.length;i++){
          name.push(item.dictItemModels[i].label)
        }
        item.checkedCities = val ? name : [];
      },
      //单个选择按钮
      handleCheckedCitiesChange(value,item) {
        let checkedCount = value.length;
        item.checkAll = checkedCount === item.dictItemModels.length;
      },
      // 取消按钮
      cancel() {
        this.dialogVisible = false;
      },
      categoryClick(){
        let self=this;
        this.form.infoContent='';
        this.categoryList.forEach(function(item) {
          if(item.brandId==self.form.brandId){
            self.$set(self.form,'infoType',item.brandType);
          }
        })

      },
      //获取危险源列表
      laboratoryBrandDetailGetDetailHazardConfig(){
        let self=this;
        laboratoryBrandDetailGetDetailHazardConfig({dictCode:'lab_dangerous_source'}).then( response => {

          if (this.propsData.detailId){//编辑
            response.data.forEach(function(item){
              item.allName='全选';
              item.checkAll=false;
              item.checkedCities=[];
            })

            response.data.forEach(function(item){
              let list=[];
              //详情返回的数组
              self.form.listHazardModel.forEach(function(item2) {
                let hazardCodeName=item2.hazardCodeName.split(',')
                if (item.hazardKey==item2.hazardKey){
                  if (item.dictItemModels.length ==hazardCodeName.length){
                    item.checkAll=true;
                  }
                  item.checkedCities=hazardCodeName;
                }
              })

            })
          }else{//新增
            response.data.forEach(function(item){
              item.allName='全选';
              item.checkAll=false;
              item.checkedCities=[];
            })
          }
          this.$set(this,'conditionList',response.data)

        });
      },
      //删除危险源
      delHazard(row){
        this.form.listHazardModel = this.form.listHazardModel.filter(item => item !== row);
      },
      //危险源保存
      conditionSubmitForm(){
        //分类认定条件数据筛选
        console.log(this.conditionList)
        let list=[];
        this.conditionList.forEach(function(item) {
          let list2=[];
          let list3=[];
          if (item.checkedCities.length>0){
            item.dictItemModels.forEach(function(item2) {
              item.checkedCities.forEach(function(item3) {
                if (item3==item2.label){
                  list2.push(item2.value)
                  list3.push(item2.label)
                }
              })
            })
            list.push({hazardKey:item.hazardKey,hazardName:item.hazardName,hazardCode:list2.join(','),hazardCodeName:list3.join(',')})
          }
        })
        if(!list[0]){
          this.msgError('请勾选危险源分类')
          return
        }
        this.$set(this.form, 'listHazardModel',list)
        this.$set(this, 'dialogVisible',false)


      },
      //查询信息类目列表
      getCategoryList(){
        let obj={
          page: 1,
          pageSize:100,
          isShow:1,
        }
        laboratoryInfoBrandList(obj).then( response => {
          this.$set(this,'tabsList',response.data.records);
          this.$set(this,'categoryList',response.data.records);
          this.$set(this,'infoType',response.data.records[0]?response.data.records[0].brandType+'':'');

        });
      },
      // 返回按钮
      backPage(){
        this.$parent.handleClick('','','back');
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.detailId) {
              laboratoryBrandDetailUpdate(this.form).then( response => {
                this.msgSuccess(response.message);
                this.open = false;
                this.$parent.handleClick('','','back');
              });
            } else {
              laboratoryBrandDetailAdd(this.form).then( response => {
                this.msgSuccess(response.message);
                this.open = false;
                this.$parent.handleClick('','','back');
              });
            }
          }
        });
      },
      //上传
      handleAvatarSuccess(res, file) {
        this.form.infoContent = res.data.url;
        this.$forceUpdate()
      },
      beforeAvatarUpload(file) {
        return new Promise((resolve, reject) => {
          if (file.type == 'image/png') {
            let reader = new FileReader()
            reader.readAsDataURL(file) // 必须用file.raw
            reader.onload = e => { // 让页面中的img标签的src指向读取的路径
              let img = e.target.result;
              const image = new Image()
              image.src=img
              image.onload = _=>{
                if(image.width <= 630 && image.height <= 78){
                  resolve()
                }else{
                  this.msgError('尺寸限制为最大630*78px，支持PNG格式')
                  reject();
                }
              }
            }
          }else{
            this.msgError('请上传PNG格式');
            reject();
          }
        })
      },

    },
  }
</script>

<style scoped lang="scss">
  .notice-addPage{
    .content-box{
      flex:1;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      padding:20px;
    }
    .danger-tip{
      font-weight: 400;
      font-size: 16px;
      color: #FF0000;
      line-height: 24px;
      text-align: left;
      margin-top: 8px;
    }
    .danger-table{
      width: 600px;
      margin-left: 120px;
    }
    .danger-add{
      width: 500px;
      height: 40px;
      border-radius: 4px 4px 4px 4px;
      border: 1px dashed #0183FA;
      margin-left: 170px;
      font-weight: 400;
      font-size: 14px;
      color: #0183FA;
      line-height: 40px;
      text-align: center;
      margin-top: 20px;
      cursor: pointer;
    }
    .certificate-avatar-uploader{
      i{
        width:80px;
        height:80px;
        line-height:80px;
        text-align: center;
        border:1px solid #e0e0e0;
        border-radius:4px;
      }
      img{
        width:240px;
        height:240px;
      }
    }

  }
  .classify-name{
    margin-bottom: 20px;
    margin-left: 34px;
    >i{
      color: #ff4949;
      margin-right: 4px;
    }
    color: #333;
    font-size: 14px;
    font-weight: 500;
  }
  .classify{
    width: 820px;
    height: 236px;
    overflow-y: auto;
    margin-left: 38px;
    .classify-li{
      min-height: 80px;
      display: flex;
      justify-content: flex-start;
      border: 1px solid #E0E0E0;
      border-top: 0;
      .classify-li-l{
        width: 150px;
        min-height: 80px;
        display: flex;
        justify-content: center;
        align-items: center;
        border-right: 1px solid #E0E0E0;
        background: #F5F5F5;
      }
      .classify-li-r{
        .el-checkbox{
          margin:4px 30px 4px 0;
        }
        flex: 1;
        >p{
          display: flex;
          align-items: center;
          padding-left: 14px;
          box-sizing: border-box;
        }
        >p:nth-of-type(1){
          min-height: 40px;
          border-bottom:1px solid #E0E0E0;
          background: #F5F5F5;
        }
        >p:nth-of-type(2){
          min-height: 40px;
        }
      }
    }
    .classify-li:first-child{
      border-top: 1px solid #E0E0E0;
    }
  }
</style>
