<template>
  <div v-loading="fullLoading" class="content">
    <div class="top">
      <div class="engineering-title">
        <div>{{ $t('engineering.add') }}</div>
      </div>
      <div class="button-group">
        <!--        出图-->
        <el-button type="primary" icon="el-icon-circle-check" @click="submitForm" :loading="submitLoading">
          {{ $t('engineering.plot') }}
        </el-button>
        <!--        取消-->
        <el-button @click="cancel" icon="el-icon-remove-outline">
          {{ $t('common.cancel') }}
        </el-button>
      </div>
    </div>

    <div class="card">
      <el-form class="plot-form" ref="form" :model="form" :rules="rules" label-position="top">
        <el-row :gutter="20">
          <el-col :span="12">
            <!--            关联项目-->
            <Select required prop="projectId" :data="projectList" :label="$t('follow.relatedProject')" :clearable="false"
                    :styleObj="{ width: '100%' }" @change="projectChange"></Select>
          </el-col>
          <el-col :span="6">
            <!--            语言-->
            <Select required prop="language" :data="dict.type.language" :label="$t('common.language')" :clearable="false"
                    :styleObj="{ width: '100%' }"></Select>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <!--            关联报价-->
            <Select prop="quotationNo" :data="quotationList" :label="$t('engineering.quotation')"
                    :styleObj="{ width: '100%' }" @change="quotationChange"></Select>
          </el-col>
          <el-col :span="4">
            <!--            版本-->
            <Select prop="version" :data="versionList" :clearable="false" :label="$t('quotation.version')"
                    :styleObj="{ width: '100%' }" @change="getModelList"></Select>
          </el-col>
          <el-col :span="6">
            <!--            电梯型号-->
            <Select prop="elevatorModelId" :data="elevatorModelList"
                    :label="$t('elevatorModel.elevatorModel')" :styleObj="{ width: '100%' }"
                    @change="elevatorModelChange"></Select>
          </el-col>
          <el-col :span="6">
            <!--            添加电梯-->
            <el-button :disabled="!this.form.elevatorModelId" style="margin-top: 24px;" type="primary" icon="el-icon-plus"
                       size="mini" @click="addElevator">
              {{ $t('elevator.addElevator') }}
            </el-button>
          </el-col>
        </el-row>
        <!--        新增电梯-->
        <el-button style="margin-top: 24px;" type="primary" icon="el-icon-plus" size="mini"
                   @click="handleAddElevator">{{ $t('elevator.add') }}
        </el-button>
        <el-table class="elevator-table" :data="elevatorTableList" max-height="400px" border
                  :header-cell-style="{ background: '#F4F6F8', color: '#92A2B5' }">
          <el-table-column label="No." type="index" width="50" align="center"></el-table-column>
          <!--          电梯型号-->
          <el-table-column prop="elevatorModel" :label="$t('elevatorModel.elevatorModel')" min-width="200px"></el-table-column>
          <!--          电梯编号-->
          <el-table-column prop="elevatorCode" :label="$t('quotation.elevatorNo')" min-width="200px"></el-table-column>
          <!--          排列序号-->
          <el-table-column prop="sortNumber" :label="$t('elevator.sortNum')" min-width="200px"></el-table-column>
          <!--          添加方式-->
          <el-table-column prop="addType" :label="$t('engineering.addType')" min-width="200px" align="center">
            <template slot-scope="scope">
              <span>{{ formatDict(scope.row.addType, dict.type.plot_add_type) }}</span>
            </template>
          </el-table-column>
          <!--          规格-->
          <el-table-column prop="specification" :label="$t('engineering.specification')" width="600px" show-overflow-tooltip></el-table-column>
          <!--          创建时间-->
          <el-table-column prop="createTime" :label="$t('common.createTime')" min-width="200px"></el-table-column>
          <!--          操作-->
          <el-table-column :label="$t('common.operate')" width="250px" fixed="right" align="center">
            <template slot-scope="scope">
              <!--              查看-->
              <el-button size="mini" type="text" icon="el-icon-view" @click="handleViewElevator(scope.row)">
                {{ $t('common.view') }}
              </el-button>
              <!--              编辑-->
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEditElevator(scope.row)">
                {{ $t('common.edit') }}
              </el-button>
              <!--              删除-->
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteElevator(scope.row)">
                {{ $t('common.delete') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <span v-if="elevatorTableList && elevatorTableList.length > 1">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-row :gutter="20">
              <el-col :span="24">
                 <!--            出图模板选择-->
                 <Select required prop="templateId" :data="templateList" @change="templateChange" :disabled="imageLoading"
                         :label="$t('engineering.templateSelect')" :styleObj="{ width: '100%' }"></Select>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
               <!--            共井道材质-->
                <Select required prop="commonShaftMaterial" :data="dict.type.shaft_material" :disabled="imageLoading"
                        :label="$t('engineering.commonShaftMaterial')" :styleObj="{ width: '100%' }"></Select>
              </el-col>
            </el-row>
          </el-col>
            <el-col :span="18">
              <div class="template-pic" >
                    <el-card :body-style="{ padding: '0px !important',width: '30.5vw',height:'30.5vw' }">
                      <el-image v-loading="imageLoading" fit="fill" style="width: 30.5vw;height: 30.5vw;border-radius: 6px;margin: 0px" :src="url" :preview-src-list="[url]" @load="handleImageLoad" @error="handleImageLoad">
                        <div slot="error">
                          <div class="err-div" style="width: 30.5vw;height: 30.5vw">{{ $t('quotation.noImg') }}</div>
                        </div>
                        <div slot="placeholder">
                          <div class="err-div" style="width: 30.5vw;height: 30.5vw">{{ $t('quotation.noImg') }}</div>
                        </div>
                      </el-image>
                    </el-card>
               </div>
            </el-col>
         </el-row>
        </span>
      </el-form>
    </div>
  </div>
</template>

<script>
import {addEngineering, getEngineering} from "@/api/business/civil/engineering";
import {listAllTemplates} from "@/api/business/civil/templates";
import {listAllProject} from "@/api/business/crm/project";
import {listByProjectId} from "@/api/business/quotation/quotation";
import {listByQuotationNoVersion} from "@/api/business/quotation/specification";
import store from '@/store/index'
import {parseTime} from "@/utils/ruoyi";
import ImageUpload from "@/components/ImageUpload/index";

export default {
  name: "Plot-add",
  components: {ImageUpload},
  dicts: ['shaft_material', 'plot_add_type', 'language'],
  data() {
    return {
      // 国家id
      countryId:null,
      // 下载文件url前缀
      baseApi: process.env.VUE_APP_BASE_API,
      id: null,
      areaId: null,
      language: this.$i18n.locale,
      fullLoading: false,
      submitLoading: false,
      form: {},
      rules: {},
      projectList: [],
      quotationList: [],
      versionList: [],
      modelList: [],
      elevatorModelList: [],
      templateList: [],
      elevatorTableList: [],
      elevatorSet: new Set(),
      file: '',
      elevatorCount: 0,
      url: '',
      imageLoading: false,
    }
  },
  async created() {
    await this.getProjectList();
    await this.getTemplateList();
    this.id = this.$route.query && this.$route.query.id ? this.$route.query.id : null;
    if(this.id){
      await this.getEngineering();
    }
  },
  activated() {
    this.getStoreElevatorInfo();
  },
  methods: {
    async getEngineering() {
      this.fullLoading = true;
      await getEngineering(this.id).then(res => {
        this.form = res.data;
        this.elevatorTableList = this.form.elevatorList;
        let countryName = '';
        switch (this.language) {
          case 'chinese':
            countryName = this.form.countryName
            break;
          case 'english':
            countryName = this.form.countryNameUS
            break;
          case 'russia':
            countryName = this.form.countryNameRU
            break;
          case 'spanish':
            countryName = this.form.countryNameES
            break;
        }
        // this.projectList = [{value: this.form.projectId, label: this.form.projectNo + ':  ' + this.form.projectName + ' - ' + countryName + ' - ' + this.form.city}]
        // if (this.form.quotationId) {
        //   this.quotationList = [{value: this.form.quotationId, label: this.form.quotationNo + ':  ' + this.form.projectName}]
        // }
        // if (this.form.version) {
        //   this.versionList = [{value: this.form.version, label: this.form.version}]
        // }
        let project = this.projectList.find(item => item.value == this.form.projectId)
        this.areaId = project.areaId;
        this.countryId = project.countryId;
      })
      this.fullLoading = false;
    },
    parseTime,
    // 获取电梯页面传过来的电梯信息
    getStoreElevatorInfo() {
      let elevatorId = this.$route.query && this.$route.query.elevatorId;
      if (elevatorId !== undefined) {
        let elevator = this.$store.state.elevators[elevatorId];
        console.log('检查电梯是否存在', this.elevatorSet, elevatorId, this.elevatorSet.has(Number(elevatorId)))
        if (this.elevatorSet.has(Number(elevatorId))) {
          console.log("重复编辑电梯", elevatorId, elevator)
          if (elevator !== undefined && elevator != null) {
            // 替换电梯列表
            for (let i = 0; i < this.elevatorTableList.length; i++) {
              if (this.elevatorTableList[i].id == elevatorId) {
                //保留创建时间
                elevator.createTime = this.elevatorTableList[i].createTime
                this.$set(this.elevatorTableList, i, elevator);
              }
            }
          } else {
            console.log("编辑电梯内存获取失败")
          }
        } else {
          console.log("新增电梯", elevatorId)
          if (elevator !== undefined && elevator != null) {
            this.elevatorSet.add(Number(elevatorId));
            elevator.createTime = parseTime(new Date(), '{y}-{m}-{d}');
            this.elevatorTableList.push(elevator);
          } else {
            console.log("新增电梯内存获取失败")
          }
        }
      }
      console.log('电梯列表', this.elevatorTableList)
    },
    formatDict(value, dictData) {
      return dictData.find(dict => dict.value == value)?.label;
    },
    // 查询项目列表
    getProjectList() {
      listAllProject({language: this.language}).then(res => {
        this.projectList = res.rows.map(item => {
          return {
            areaId: item.areaId,
            value: item.projectId,
            countryId: item.countryId,
            label: item.projectNo + ':  ' + item.projectName + ' - ' + item.countryName + ' - ' + item.city
            //  + ' - ' + item.developer
          }
        })
      })
    },
    // 根据项目查询报价列表
    getQuotationList() {
      listByProjectId(this.form.projectId).then(res => {
        this.quotationList = res.data.map(item => {
          return {
            value: item.quotationNo,
            label: item.quotationNo + ':  ' + item.projectName,
            version: item.version
          }
        })
      })
    },
    handleImageLoad(e){
      console.log('图片加载完成', e)
      this.imageLoading = false
    },
    // 根据报价查询电梯型号列表
    getModelList() {
      if (this.form.quotationNo && this.form.version) {
        let form = {
          quotationNo: this.form.quotationNo,
          version: this.form.version
        }
        this.elevatorModelList = []
        this.$set(this.form, 'elevatorModelId', null);
        listByQuotationNoVersion(form).then(res => {
          this.modelList = res.data;
          this.elevatorModelList = res.data.map(item => {
            return {
              value: item.elevatorCode + ':' + item.elevatorModelId,
              label: item.elevatorCode + ':  ' + item.elevatorModel
            }
          })
          this.form.elevatorModelId = this.elevatorModelList[0]?.value
        })
      }
    },
    // 查询模板列表
    getTemplateList() {
      listAllTemplates().then(res => {
        this.templateList = res.rows.map(item => {
          return {
            value: item.id,
            label: item.templateName + ' (' + item.elevatorPosition + ')',
            file: item.file,
            elevatorQuantity: item.elevatorQuantity
          }
        })
      })
    },
    templateChange(row) {
      if (this.imageLoading) {
        return;
      }
      this.imageLoading = true;
      if (row && row.value) {
        let template = this.templateList.find(item => item.value == row.value)
        console.log('模板选择', template)
        this.file = template?.file || '/empty';
        this.elevatorCount = template?.elevatorQuantity
      } else {
        this.file = '/empty';
        this.elevatorCount = 0
      }
      this.url = this.baseApi + this.file + '?v=' + new Date().getTime();
    },
    // 项目改变
    projectChange(row) {
      console.log('项目改变', row)
      let project = this.projectList.find(item => item.value == row.value)
      this.areaId = project.areaId;
      this.countryId = project.countryId;
      console.log('项目改变', this.areaId)
      console.log('项目改变', this.countryId)
      this.quotationList = [];
      this.versionList = [];
      this.elevatorModelList = [];
      this.$set(this.form, 'quotationNo', null);
      this.$set(this.form, 'version', null);
      this.$set(this.form, 'elevatorModelId', null);
      if (this.form.projectId) {
        this.getQuotationList();
      }
    },
    // 报价单改变
    quotationChange() {
      this.$set(this.form, 'elevatorModelId', null);
      this.versionList = [];
      this.elevatorModelList = [];
      this.$set(this.form, 'version', null);
      if (this.form.quotationNo) {
        let quotation = this.quotationList.find(item => item.value == this.form.quotationNo);
        if (quotation.version && quotation.version.length > 0) {
          this.versionList = quotation.version.map(item => {
            return {
              label: item,
              value: item
            }
          })
          this.form.version = this.versionList[0]?.value;
          this.getModelList()
        }
      }
    },
    // 电梯型号改变
    elevatorModelChange() {
    },
    // 通过报价单添加电梯
    addElevator() {
      const elevatorData = this.modelList.find(item => (item.elevatorCode + ':' + item.elevatorModelId) == this.form.elevatorModelId);
      if (!elevatorData) {
        console.log('未找到对应的电梯')
        return;
      }
      // 获取当前最大排序编号
      let maxSort = -1
      // 判断电梯编号是否重复
      let elevatorCode = elevatorData.elevatorCode
      for (let i = 0; i < this.elevatorTableList.length; i++) {
        if (this.elevatorTableList[i].elevatorCode == elevatorCode) {
          this.$message.error(this.$t('elevator.duplicateElevatorNo'))
          return
        }
        maxSort = this.elevatorTableList[i].sortNumber > maxSort ? this.elevatorTableList[i].sortNumber : maxSort
      }

      const elevator = Object.assign({}, elevatorData);
      elevator.id = Date.now();
      // elevator.index = this.elevatorTableList.length;
      elevator.addType = '02';
      elevator.offsetX = '0';
      elevator.offsetY = '0';
      elevator.sortNumber = maxSort + 1;
      this.elevatorTableList.push(elevator)
      this.elevatorSet.add(Number(elevator.id));
      console.log('电梯列表', this.elevatorTableList)
    },
    // 新增电梯
    async handleAddElevator() {
      if (!this.form.projectId) {
        this.$message.error(this.$t('plot.selectProject'))
        return
      }
      // 获取当前最大排序编号
      let maxSort = -1
      // 缓存已存在的电梯编号
      let elevatorCodeList = []
      if (this.elevatorTableList && this.elevatorTableList.length > 0) {
        for (let i = 0; i < this.elevatorTableList.length; i++) {
          elevatorCodeList.push(this.elevatorTableList[i].elevatorCode)
          maxSort = this.elevatorTableList[i].sortNumber > maxSort ? this.elevatorTableList[i].sortNumber : maxSort
        }
      }
      store.commit('ADD_ELEVATOR_CODE', elevatorCodeList)

      let query = {
        type: 'add',
        areaId: this.areaId,
        countryId: this.countryId,
        maxSort: maxSort + 1
      }
      await this.$tab.closePage({name: 'Elevator', path: '/civil/elevator'})
      await this.$tab.openPage(this.$t('elevator.add'), '/civil/elevator', query);
    },
    // 查看电梯
    async handleViewElevator(row) {
      store.commit('PUT_ELEVATOR', row)
      let query = {
        type: 'view',
        areaId: this.areaId,
        elevatorId: row.id,
        countryId: this.countryId,
      }
      await this.$tab.closePage({name: 'Elevator', path: '/civil/elevator'})
      await this.$tab.openPage(this.$t('elevator.view'), '/civil/elevator', query);
    },
    // 编辑电梯
    async handleEditElevator(row) {
      // 缓存已存在的电梯编号
      let elevatorCodeList = []
      if (this.elevatorTableList && this.elevatorTableList.length > 0) {
        for (let i = 0; i < this.elevatorTableList.length; i++) {
          if (this.elevatorTableList[i].elevatorCode != row.elevatorCode) {
            elevatorCodeList.push(this.elevatorTableList[i].elevatorCode)
          }
        }
      }
      store.commit('ADD_ELEVATOR_CODE', elevatorCodeList)

      store.commit('PUT_ELEVATOR', row)
      let query = {
        type: 'edit',
        areaId: this.areaId,
        elevatorId: row.id,
        countryId: this.countryId,
      }
      await this.$tab.closePage({name: 'Elevator', path: '/civil/elevator'})
      await this.$tab.openPage(this.$t('elevator.edit'), '/civil/elevator', query);
    },
    // 删除电梯
    handleDeleteElevator(row) {
      this.elevatorTableList = this.elevatorTableList.filter(item => item.id != row.id)
      this.elevatorSet.delete(Number(row.id));
      store.commit('DEL_ELEVATOR', {id: row.id})
    },
    // 取消
    cancel() {
      this.$tab.closePage();
    },
    // 提交出图
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          // 电梯必填
          if (this.elevatorTableList.length == 0) {
            this.$modal.msgError(this.$t('elevator.required'));
            return;
          }
          // 电梯数量大于1时
          if (this.elevatorTableList.length > 1) {
            // 校验数量
            if (this.elevatorTableList.length != this.elevatorCount) {
              this.$modal.msgError(this.$t('elevator.countError'));
              return;
            }
          } else {
            this.form.templateId = null;
            this.form.commonShaftMaterial = null;
          }
          // 校验电梯参数是否为空（可以为0）
          let flag = false;
          for (let i = 0; i < this.elevatorTableList.length; i++) {
            let elevator = this.elevatorTableList[i].paramList.find(item => !item.paraValue && item.paraValue != '0')
            if (elevator){
              flag = true
              this.$modal.msgError(this.$t('quotation.elevatorNo') + "'"+ this.elevatorTableList[i].elevatorCode +"'" + this.$t('engineering.checkNullParam'));
              break
            }
          }
          if (flag){
            return
          }
          this.elevatorTableList.forEach(item => item.quantity = item.elevatorNumber);
          this.submitLoading = true;
          this.form.elevatorList = this.elevatorTableList;
          this.form.areaId = this.areaId;
          addEngineering(this.form).then(response => {
            if (response.code == 200) {
              this.$modal.msgSuccess(this.$t('common.addSuccess'));
              this.cancel();
            } else {
              this.$modal.msgError(response.msg);
            }
            this.submitLoading = false;
          }).catch(() => {
            this.submitLoading = false;
          });

        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .plot-form .el-form-item--medium .el-form-item__label {
  line-height: 16px;
}

::v-deep .no-plus .el-upload--picture-card {
  display: none;
}

.content {
  padding: 24px;
  position: relative;

  .top {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .engineering-title {
      font-size: 18px;
      color: #000000;
      line-height: 21px;
      font-weight: bold;
    }

    .button-group {
      display: flex;
    }
  }

  .card {
    margin-top: 16px;
    background-color: white;
    padding: 24px;
    box-shadow: 0px 2px 10px 0px #CED6DD;
    border-radius: 6px;

    .elevator-table {
      margin: 24px 0 40px 0;
    }
  }

  .template-pic {
    bottom: 48px;
    left: 30%;
    width: 30.5vw;
  }
}

.err-div {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  text-align: center; /* 文字水平居中 */
  height: 30.5vw; /* 设置容器高度 */
  width: 30.5vw; /* 设置容器宽度 */
  /*border: 1px solid #ccc; !* 边框 *!*/
  user-select: none;
  background-color: rgb(245, 247, 250);
}
</style>
