<template>
  <div class="app-container" >
    <!--价格表设定-->
    <el-form ref="formSelectOpt" :model="formJGB" label-width="120px" >
      <el-row>
        <el-col :span="8">
          <Select :label="$t('elevatorModel.areaName')" prop="areaId" :labelProp="localLabel" valueProp="areaId" :data="areaOps" :placeholder="$t('common.pleaseSelect')" disabled/>
        </el-col>
        <el-col :span="8">
          <Select :label="$t('elevatorModel.elevatorTypeName')" prop="elevatorType" :data="dict.type.elevator_type" :placeholder="$t('common.pleaseSelect')" disabled/>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('elevatorModel.elevatorModel')" prop="elevatorModel">
            <el-input v-model="formJGB.elevatorModel" :placeholder="$t('common.pleaseInput')" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <ImportModal style="margin-left:10px" title="导入" icon="el-icon-download" fileName="区域电梯参数信息导入模板"
                       :close="getList" :defaultParams="{id:1}"/>
          <el-button type="primary" @click="submitSelectForm">导出</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-tabs type="border-card">
          <el-tab-pane :label=" $t('elevatorModel.JJManage')" style="height: 540px;overflow: auto">
            <el-col :span="12" style="padding-left: 0px;margin-bottom: 10px" >
              <el-button @click="cancel">{{ }}新增行</el-button>
              <el-button @click="cancel">{{ }}删除行</el-button>
              <el-button @click="cancel">{{ $t('common.cancel') }}复制行</el-button>
            </el-col>
            <el-col :span="12" style="text-align:right;padding-right: 10px;margin-bottom: 10px" >
              <el-button type="primary" @click="submitSelectForm">{{ $t('common.confirm') }}</el-button>
              <el-button @click="cancel">{{ $t('common.cancel') }}</el-button>
            </el-col>
            <el-table
              ref="table"
              :data="formJGB.baseData"
              v-loading="JJLoading"
              row-key="id"
              @selection-change="handleSelectionChange"
              class="page-table"
              :row-style="{'height':'8px'}"
              max-height="540px"
              :border="true"
              :header-cell-style="{'background-color':'#F4F6F8','border-right':'1px solid #dfdcdc','color':'#92A2B5'}">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column prop="ratedLoadCapacity" label="额定载重(kg)" width="200px">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.ratedLoadCapacity" style="width: 92%;"
                                   :disabled="disabled" :min="0" :max="99999"
                                   :precision="2" class="custom-number" />
                </template>
              </el-table-column>
              <el-table-column prop="ratedSpeed" label="额定速度(m/s)" width="200px">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.ratedSpeed" style="width: 92%;"
                                   :disabled="disabled" :min="0" :max="99999"
                                   :precision="2" class="custom-number" />
                </template>
              </el-table-column>
              <InputNumberColumn prop="standardDoorWidth" label="开门宽"/>
              <InputNumberColumn prop="standardDoorHeight" label="开门高"/>
              <InputNumberColumn prop="maxLiftingHeight" label="最大提示高度"/>
              <InputNumberColumn prop="standardFloors" label="标准层站数"/>
              <InputNumberColumn prop="basicPrice" label="基础价格"/>
              <InputNumberColumn prop="addOnefloorPrice" label="层站加价"/>
              <InputNumberColumn prop="subtractOnefloorPrice" label="层站减价"/>
            </el-table>


          </el-tab-pane>
          <el-tab-pane :label=" $t('elevatorModel.XPManage')" style="height: 540px;overflow: auto">
            <el-col :span="12" style="padding-left: 80px" >
              <h3>选配项目</h3>
              <el-table
                ref="table"
                :data="formJGB.JJData"
                v-loading="JJLoading"
                row-key="id"
                @selection-change="handleSelectionChange"
                class="page-table"
                :row-style="{'height':'8px'}"
                max-height="520px"
                :border="true"
                :header-cell-style="{'background-color':'#F4F6F8','border-right':'1px solid #dfdcdc','color':'#92A2B5'}">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column prop="contactName" :label="$t('contact.name')" width="200px">
                  <template slot-scope="scope">
                    <el-input v-model.trim="scope.row.contactName" :disabled="type == 'view'"
                              maxlength="30"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="phone" :label="$t('contact.phone')" width="200px">
                  <template slot-scope="scope">
                    <el-input v-model.trim="scope.row.phone" :disabled="type == 'view'"
                              maxlength="30"></el-input>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-tab-pane>
        </el-tabs>
      </el-row>
    </el-form>

  </div>
</template>


<script>
import { getModel, addModel, updateModel,getArea,getModelParam,getModelSelecItem,getModelStandItem,getModelJgbInfo } from "@/api/business/crm/elevatorModel.js";
import { updateModelParam } from "@/api/business/crm/areaPara.js";
import { updateModelSelect } from "@/api/business/crm/areaSelectItem.js";
import { updateModelStand } from "@/api/business/crm/standard.js";

import { listLibrary } from "@/api/business/crm/paralibrary/library.js";

import ImportModal from "../../../components/ImportModal/index";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getCountryByAreaId} from "@/api/system/user";
import {getAreaTree} from "@/api/common/common";
import InputColumn from "../../../components/element/table/InputColumn";
import InputNumberColumn from "../../../components/element/table/InputNumberColumn";

export default {
  name: "PriceForm",
  components:{InputNumberColumn, InputColumn, Treeselect, ImportModal},
  dicts: ['input_type','para_category','elevator_type','status_switch'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      libraryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        areaId: null,
        elevatorType: null,
        elevatorModel: null,
        status: null,
      },
      // 表单参数
      form: {
        areaId:null,
        areaName: null,
        elevatorType: null,
        elevatorModel: null,
        remark: null,
        status: null,
      },
      // 表单校验
      rules:{
        areaId:[
          {required:true, message: this.$t('common.pleaseSelect'), trigger:'blur'}
        ],
        elevatorType:[
          {required:true, message: this.$t('common.pleaseSelect'), trigger:'blur'}
        ],
        elevatorModel:[
          {required:true, message: this.$t('common.pleaseInput'), trigger:'blur'}
        ],
        status:[
          {required:true, message: this.$t('common.pleaseSelect'), trigger:'blur'}
        ],
        remark:[
          {required:true, message: this.$t('common.pleaseInput'), trigger:'blur'}
        ],
      },
      selections:[],
      // 地区下拉
      areaOps: [],
      // 地区树
      areaTree: [],
      localLabel:"",
      localParaLabel:'',
      localSelectLabel:"",
      openJGB:false,
      formJGB:{},
      JJLoading:false,
      selectionsJGB:[]
    };
  },
  created() {
    this.initData()
    this.setLabel();
    this.getAreaOps();
    this.getAreaTree();

  },
  methods: {
   async initData(){
      this.elevatorModelId = this.$route.query && this.$route.query.id;

      const response = await getModelJgbInfo(this.elevatorModelId);
      //处理数据，赋值为穿梭框选中集合
      this.formJGB = response.data;
      this.openJGB = true;
      //this.title = this.$t('paraLibrary.editParameter');
      this.title = "编辑价格表"
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = this.$t('paraLibrary.addParameter');
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids

      const response = await getModel(id);
      this.form = response.data;
      this.open = true;
      this.title = this.$t('paraLibrary.editParameter');
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateModel(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.editSuccess'));
              this.open = false;
              this.getList();
            });
          } else {
            addModel(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.addSuccess'));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.queryParams.language = this.$i18n.locale;
      this.download('business/library/export', {
        ...this.queryParams
      }, `library_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {  },
    /** 行link操作 */
    handleView(row) {
      this.$tab.openPage(this.$t('paraLibrary.paraSelectItems'), '/crmManagement/library-view/index/' + row.id);
    },
    // 字典值format
    formatDict(value,dictType){
      let labelStr = '';
      for(let i =0;i< this.dict.type[dictType].length;i++){
        let item = this.dict.type[dictType][i]
        if(item.value == value){
          labelStr = item.label;
          break;
        }
      }
      return  labelStr;
    },

    // 获取地区树
    getAreaTree() {
      getAreaTree().then(response => {
        this.areaTree = response.data;
        console.log('allAreaList', this.areaTree)
        // 将根节点设置 isDisabled: true
        // if (this.areaTree.length > 0) {
        //   this.areaTree[0].isDisabled = true;
        // }
      });
    },
    async getAreaOps() {
      const response = await getArea();
      this.areaOps = response.data;
    },
    //设置本地语音label
    setLabel(){
      let currentLocale = window.VueI18n.locale;
      switch (currentLocale) {
        case "chinese": this.localLabel ="areaName"
          this.localParaLabel ="paraName"
          this.localSelectLabel ="label"
          break
        case "english": this.localLabel ="areaNameUS"
          this.localParaLabel ="paraNameUS"
          this.localSelectLabel ="labelUS"
          break
        case "russia": this.localLabel ="areaNameRU"
          this.localParaLabel ="paraNameRU"
          this.localSelectLabel ="labelRU"
          break
        case "spanish": this.localLabel ="areaNameES"
          this.localParaLabel ="paraNameES"
          this.localSelectLabel ="labelES"
          break
      }
    },
    //改变语言
    changeLanguage(id){
      let res = this.selectLabelList(this.areaOps,id,this.localLabel,"areaId");
      return res?res:"-"
    },
    //跳转
    jump() {
      let query = {
        test: 's'
      };
      this.$router.push({path: "/system/notice", query: query});
    },
    //参数选配
    async handleParam(row) {
      this.resetXP();
      const id = row.id || this.ids
      const response = await getModelParam(id);
      if(response.data){
        //处理数据，赋值为穿梭框选中集合
        this.formXP = response.data;
        if(this.formXP.paraSelect){
          //已经保存过了
          this.paraSelectList = this.formXP.paraSelect.map(it=>it.paramId)
        }
      }
      this.openXP = true;
      this.title = this.$t('paraLibrary.editParameter');

      setTimeout(()=>{
        this.transferQuery = "00";
        this.$refs.paraSelect.$refs.leftPanel.query = "00";
      },200)

    },
    //参数选项
    async handleSelect(row) {
      this.resetSelectOpt();
      const id = row.id || this.ids
      const response = await getModelSelecItem(id);
      //处理数据，赋值为穿梭框选中集合
      this.formSelectOpt = response.data;

      this.openSelectOpt = true;
      this.title = this.$t('paraLibrary.editParameter');

    },
    resetXP() {
      this.formXP = {
        areaId: null,
        elevatorType: null,
        elevatorModel: null,
        remark: null,
        status: null,
        paraSelect:[],
      }
      this.paraSelectList = []
    },
    resetSelectOpt() {
      this.formSelectOpt = {
        areaId: null,
        elevatorType: null,
        elevatorModel: null,
        remark: null,
        status: null,
        TabsList:[],
      }
    },
    resetStand() {
      this.formStand = {
        areaId: null,
        elevatorType: null,
        elevatorModel: null,
        remark: null,
        status: null,
        tabsList:[],
      }
    },
    //获取全部的参数列表
    getParamLibraryList() {
      let params;
      params = {
        pageNum:0,
        pageSize:0,
        status: 0,
      };
      listLibrary(params).then(response => {
        this.paraLibraryList = response.rows;
        //处理数据让他成为穿梭框数据
        // let opts = []
        // this.paraLibraryList.some(item=>{
        //   let opt = {
        //     key:item.id,
        //     label:item[this.localParaLabel],
        //     disabled:false
        //   }
        //   opts.push(opt)
        // });
        this.paraLibraryListOpt = this.changeTransfer(this.paraLibraryList,this.localParaLabel,"id")
      });
    },
    /** 提交XP按钮 */
    submitXPForm() {
      //只有更新
      //新增之前处理数据
      this.formXP.paraSelect = [];
      this.paraSelectList.some(item=>{
        let paraLibrary = this.paraLibraryList.filter(library=> library.id == item )
        let paraSelect = {
          paraId:item,
          paramId:item,
          paraCode:paraLibrary[0].paraCode,
          elevatorModelId:this.formXP.id,
          paraName:paraLibrary[0].paraName
        };
        this.formXP.paraSelect.push(paraSelect)
      });
      this.$refs["formXP"].validate(valid => {
        if (valid) {
          updateModelParam(this.formXP).then(response => {
            this.$modal.msgSuccess(this.$t('common.editSuccess'));
            this.openXP = false;
            this.getList();
          });
        }
      });
    },
    /**获取国际化*/
    getParaLabel(value){
      let res = "-";
      let dicts = this.dict.type.para_category;
      dicts.some(it=>{
        if(it.value == value){
          res = it.label
        }
      })
      return res
    },
    /**改变编辑状态*/
    changeEditFlag(row){
      //把状态变为已改变
      row.operationFlag = 2
    },
    /** 提交设置参数选项按钮 */
    submitSelectForm() {
      this.$refs["formSelectOpt"].validate(valid => {
        if (valid) {
          updateModelSelect(this.formSelectOpt).then(response => {
            this.$modal.msgSuccess(this.$t('common.editSuccess'));
            this.openSelectOpt = false;
            this.getList();
          });
        }
      });
    },


    /**改变编辑标志并且设置修改的id*/
    setSelectId(value,row){
      //改变编辑标志
      row.operationFlag = 2
      //设置Id值
      let arrs = row.selectItemList
      arrs.some(item=>{
        if(value == item.value){
          row.paraDefaultId = item.paraSelectItemId
        }
      });
    },

    /**打开价格表编辑页面*/
    async handleJGB() {
      this.resetJGB();
      const response = await getModelJgbInfo(this.elevatorModelId);
      //处理数据，赋值为穿梭框选中集合
      this.formJGB = response.data;
      this.openJGB = true;
      //this.title = this.$t('paraLibrary.editParameter');
      this.title = "编辑价格表"
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
      this.selections = selection
    },
    // 取消按钮
    cancel() {
      this.openJGB = false;
      this.resetJGB();
    },
    resetJGB() {
      this.formJGB= {
        areaId: null,
        elevatorType: null,
        elevatorModel: null,
        remark: null,
        status: null,
        baseData:[],
        xpData:[]
      }
    },
    /** 提交默认值设定 */
    submitJGB() {
      this.$refs["formStand"].validate(valid => {
        if (valid) {
          updateModelStand(this.formStand).then(response => {
            this.$modal.msgSuccess(this.$t('common.editSuccess'));
            this.openStand = false;
            this.getList();
          });
        }
      });
    },

  }
};
</script>

<style lang="scss"  scoped>
  .paraSelect{
    ::v-deep .el-transfer-panel {
      width: 250px;
      height: 450px;
    }
    ::v-deep .el-transfer-panel__body{
      height: 390px;
      .el-transfer-panel__list{
        height: 390px;
      }
    }

  }
  .search-form{
    background: #FFFFFF;
    box-shadow: 0px 2px 10px 0px #CED6DD;
    padding: 15px 0  0 0 ;
  }
</style>
