<!--货品信息-新增-->
<template>
  <div class="accessRequirementAddPage">
    <el-form :model="form" ref="form" label-width="120px" :rules="rules">
      <el-form-item label="货物名称" prop="goodsName">
        <el-input v-model="form.goodsName" placeholder="请输入材料名称" style="width:320px;" maxlength="15" ></el-input>
      </el-form-item>
      <el-form-item label="货物类型" prop="dictValue">
        <el-select v-model="form.dictValue" placeholder="请选择" style="width:320px;">
          <el-option :label="item.dictLabel" :value="item.dictValue" v-for="(item,index) in materialTypeList" :key="index"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择规格" prop="empty">
        <div class="specification">
          <div class="specification_l">
            <li @click="specificationbtn(item,index)" v-for="(item,index) in specificationList" :class="{on: index == currentIndex}">{{item.specName}}</li>
          </div>
          <div class="specification_r">
            <el-checkbox-group v-model="checkedCities">
              <el-checkbox  @change="handleCheckedCitiesChange(item2)" v-for="item2 in specificationChildList" :label="item2.specValue" :key="item2.id">{{item2.specValue}}</el-checkbox>
            </el-checkbox-group>
          </div>
          <div style="margin-left: 20px;margin-top: 20px;">
            <p class="inquire-button-one" @click="specificationAdd">添加</p>
          </div>
        </div>
      </el-form-item>

      <el-form-item label="规格配置" prop="relationType" v-if="tableData">
        <div class="deploy">
          <el-table  style="width: 100%" border :data="tableData">
            <template v-for="(item,index) in tableHead">
              <el-table-column :prop="item.key" :label="item.name" :key="index"></el-table-column>
            </template>
            <el-table-column label="最低压力值" align="left" width="260" prop="minValue" >
              <template slot-scope="scope">
                <el-input v-model="scope.row.minValue" style="display: inline-block" placeholder="请输入最低压力值" maxlength="3" @blur="pressureFun(scope.row,scope.row.minValue)"></el-input>
                <span> Mpa</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="left" width="120">
              <template slot-scope="scope">
                <div class="button-box">
                  <p @click="specificationDelete(scope.row)" v-hasPermi="['system:permit:remove']">删除</p>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form-item>
      <div class="bottom-button-box">
        <p class="reset-button-one" @click="backPage">取消</p>
        <p class="inquire-button-one" @click="submitForm">提交</p>
      </div>
    </el-form>
  </div>
</template>

<script>
import { materialdata,materialdataPut } from "@/api/laboratory/accessRequirement"
import {
  airbottleGoogsAdd,
  gasCategoryList,
  airbottleGoogsAnew,
  specificationList, qualificationApplyDetail, airbottleGoogsDetail
} from '@/api/gasManage3_0/gasManage'
export default {
  name: 'accessRequirementAddPage',
  props:{
    pageData:{},
  },
  data() {
    const empty=(rule, value, callback) => {
      callback();
    }
    return {
      loading:false,
      status:0,
      form:{
        id:"",
        goodsName:"",
        typeId:'',
        dictValue:'',
        maps:[],

      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 1000,
      },
      materialTypeList:[],
      checkedCities: [],
      currentIndex: 0,
      specificationList: [],
      specificationChildList:[],
      tableData:null,
      // 表头数据
      tableHead: [
        // {
        //   key: 'name0', name: '气体级别'
        // },
        // {
        //   key: 'name1', name: '气体规格'
        // },
      ],
      tablist:[],
      // 表单校验
      rules: {
        goodsName: [
          { required: true, message: "请输入货物名称", trigger: "change" }
        ],
        dictValue: [
          { required: true, message: "请选择货物类型", trigger: "change" }
        ],
        empty:[
          { required: true, validator:empty, trigger: "change" },
        ],


      },

    }
  },

  methods: {
    //添加最低压力值
    pressureFun(row,val){
      console.log(row)
      console.log(val)
      row.minValue=val
    },
    //删除规格配置
    specificationDelete(row){
      this.tableData.splice(this.tableData.indexOf(row),1);
    },
    //气瓶类目
    gasCategoryList(){
      let _this=this;
      gasCategoryList().then( response => {
        let res=response.rows;
        _this.materialTypeList=res;
      });
    },
    //选择规格
    specificationbtn(row,index){
      let _this=this;
      _this.currentIndex = index;
      _this.specificationList.forEach(function(item){
        if(row.id==item.id){
          _this.specificationChildList=item.detailVos
        }
      })
    },


    //复选选择规格
    handleCheckedCitiesChange(d) {
      let _this=this;


      for(let i=0;i<_this.specificationList.length;i++){

        for(let o=0;o<_this.specificationList[i].detailVos.length;o++){

          if(d.id == _this.specificationList[i].detailVos[o].id){

            _this.specificationList[i].detailVos[o].checkType = !_this.specificationList[i].detailVos[o].checkType;
          }
        }
      }
      if(d.checkType==true){
        _this.tablist.push(d)
      }else if(d.checkType==false){
        _this.tablist.splice( _this.tablist.indexOf(d),1);
      }
      console.log( _this.tablist)

    },
    //规格添加按钮
    specificationAdd(){
      let _this=this;
      if(_this.tablist.length<=0){
        this.msgError('请先选择规格!')
        return
      }
      if(_this.tablist.length<2){
        this.msgError('至少选择两种规格!')
        return
      }
      //转换成排序数组
      let arr=_this.sortArr(_this.tablist,'specId')
      console.log("arr",arr);
      let data=_this.multiplyData(arr)
      console.log(data)

      let list = [];
      let num=0;
      for(let i=0;i<data.length;i++){
        num=0;
        let obj ={};
        for(let o=0;o<data[i].length;o++){

          obj['id'+o] = data[i][o].id;
          obj['name'+o] =data[i][o].specValue;
          obj['bigNum'] =num;
          num++;
        }
        list.push(obj);
      }
      for(let i=0;i<list.length;i++){
        list[i].minValue = '';
      }
      console.log(_this.specificationList)
      let buttonList = [];
      for(let i=0;i<_this.specificationList.length;i++){
        for(let o=0;o<_this.specificationList[i].detailVos.length;o++){
          if(_this.specificationList[i].detailVos[o].checkType){
            let obj = {
              name:_this.specificationList[i].specName,
              key:'name',
            };
            buttonList.push(obj);
            break
          }
        }
      }
      buttonList.forEach(function(item,index) {
          item.key='name'+index
      })
      this.$set(this,"tableHead",buttonList)
      this.$set(this,"tableData",list)
      console.log("tableHead",buttonList)
      console.log("list",list)
    },
    multiplyData(newArrData) {
      let len = newArrData.length;
      // 当数组长度大于等于2时
      if (len >= 2) {
        // 第一个数组的长度
        let len1 = newArrData[0].length;
        // 第二个数组的长度
        let len2 = newArrData[1].length;
        //  申明一个新数组,做数据暂存
        let items = new Array();
        // 申明新数组的索引
        let index = 0;
        // 2层嵌套循环,将组合放到新数组中
        for (var i = 0; i < len1; i++) {
          for (var j = 0; j < len2; j++) {
            if (items.length < index + 1) {
              items.push([])
            }
            if (newArrData[0][i] instanceof Array) {
              items[index] = items[index].concat(newArrData[0][i].concat(newArrData[1][j]));
            } else {
              items[index] = items[index].concat([newArrData[0][i], newArrData[1][j]]);
            }
            index++;
          }
        }
        // 将新组合的数组并到原数组中
        let newArr = new Array(len - 1);
        for (let i = 2; i < newArrData.length; i++) {
          newArr[i - 1] = newArrData[i];
        }
        newArr[0] = items;
        // 执行回调
        return this.multiplyData(newArr);
      } else {
        console.log(newArrData[0]);
        return newArrData[0];
      }
    },
    sortArr(arr, str) {
      var _arr = [],
        _t = [],
        // 临时的变量
        _tmp;

      // 按照特定的参数将数组排序将具有相同值得排在一起
      arr = arr.sort(function (a, b) {
        var s = a[str],
          t = b[str];

        return s < t ? -1 : 1;
      });

      if (arr.length) {
        _tmp = arr[0][str];
      }
      // console.log( arr );
      // 将相同类别的对象添加到统一个数组
      for (var i in arr) {
        if (arr[i][str] === _tmp) {
          _t.push(arr[i]);
        } else {
          _tmp = arr[i][str];
          _arr.push(_t);
          _t = [arr[i]];
        }
      }
      // 将最后的内容推出新数组
      _arr.push(_t); //获取到所有整合数据
      // console.log(_arr);//可以得到图三
      // 终极整合
      var integration = [];
      _arr.forEach((item) => {
        var eee = { name: "", data: [] };
        item.forEach((self) => {
          if (eee.specId != self.specId) {
            eee.specId = self.specId;
            eee.data.push(self);
          } else {
            eee.data.push(self);
          }
        });
        integration.push(eee);
      });
      //console.log(integration);//图二
      // return integration;
      return  _arr
    },


    //单选事件
    radioChange(e){
      console.log(e)
      if(e==1){//上传材料

      }else if(e==2){//关联材料
        this.form.fileType=[];
        this.form.fileTypeName='';
      }
    },

    //返回
    backPage(){
      this.$parent.handleClick('','','back');
      this.$parent.getList();
    },
    //选择规格列表
    getList(){
      let _this=this;
      specificationList(_this.queryParams).then( response => {
        let res=response.rows;
        _this.specificationList=res;
        let buttonList = [];
        _this.specificationList.forEach(function(item,index){
          if(index==0){
            _this.specificationChildList=item.detailVos
          }
        })
        if(this.status==1){//编辑
          _this.specificationList.forEach(function(item,index){
            if(index==0){
              _this.specificationChildList=item.detailVos
            }
            let obj = {
              name:item.specName,
              key:'name'+index,
            };
            buttonList.push(obj);
          })
          this.$set(this,"tableHead",buttonList)
        }


      });
    },
    /* 详情 */
    getInfo(id){
      let _this=this;
      airbottleGoogsDetail(id).then( response => {
        let res=response.data;
        if(response.code==200){
          _this.form=res;
          _this.form.dictValue= _this.form.typeId+''
          _this.tableData=res.maps
        }
      });

    },
    //提交
    submitForm(){
      let _this = this;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(!_this.tableData){
            _this.msgError("请选择规格!")
            return
          }
          _this.tableData.forEach(function(item,index) {
              item.minValue=Number(item.minValue)
          })
          _this.form.typeId= _this.form.dictValue;
          _this.form.maps=_this.tableData;


          if(_this.status==0){//添加
            airbottleGoogsAdd(_this.form).then(response => {
              _this.msgSuccess("成功");
              _this.backPage();
            });
          }else if(_this.status==1){//编辑
            airbottleGoogsAnew(_this.form).then(response => {
              _this.msgSuccess("成功");
              _this.backPage();
            });
          }

        }
      })
    }

  },
  mounted(){
    this.status=this.pageData.status
    if( this.status==1){
      this.getInfo(this.pageData.id);
    }
    this.gasCategoryList()
    this.getList()
  },
}
</script>

<style scoped lang="scss">
.el-input--medium{
  display: inline-block;
  width: 160px;
  >input{
    border: none;
  }
}

.accessRequirementAddPage{
  flex:1;
  box-shadow: 0 0 8px 2px rgba(0, 0, 0, 0.1);
  padding:50px 0 50px 60px!important;
  border-radius: 10px;
  /*选择规格*/
  .specification{
    display: flex;
    justify-content: flex-start;
    .specification_l{
      border-bottom: 1px solid #E0E0E0;
      border-left: 1px solid #E0E0E0;
      border-top: 1px solid #E0E0E0;
      padding: 10px;
      box-sizing: border-box;
      >li{
        list-style-type: none;
        font-size: 14px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #333333;
        line-height: 24px;
        cursor: pointer;
      }
      .on{
        color: #0183FA;
      }
    }
    .specification_r{
      padding:4px  10px;
      box-sizing: border-box;
      border: 1px solid #E0E0E0;
    }
  }
  /*规格配置*/
  .deploy{
    width: 800px;
  }
  /*提交按钮*/
  .bottom-button-box{
    margin-top:50px;
    display: flex;
    p:nth-child(1){
      margin:0 20px 0 100px;
    }
    .inquire-button-one{
      width: 140px;
    }
  }
}
</style>
