<template>
  <div class="view-CarrierListMachineryPreparation">
    <div class="view-AerospaceCompileLineList-left">
      <MenuTree ref="tree" nodeKey="flyTaskAircaftId" :currentNodeKey="currentNodeKey" :treedata="menuTreeData" @TreeNodeclick="treeNodeClick" v-bind="treeObj"> </MenuTree>
    </div>
    <div class="view-AerospaceCompileLineList-right">
      <MissionDetail :detail="detail" />
      <div class="view-AerospaceCompileLineList-right-btn">
        <div class="view-AerospaceCompileLineList-right-btn-left">
          <el-button type="primary" @click="varietyRecommendation">品种推荐</el-button>
          <el-button type="primary" @click="openDialogVisible()">数量自动计算</el-button>
          <el-button type="primary" :disabled="currentNodeKey == 'null'" @click="addRow()">添加</el-button>
          <el-button type="primary" @click="importOperation">导入</el-button>
          <el-button type="primary" :disabled="tableData.length == 0" @click="allExport">导出</el-button>
          <el-button type="primary" :disabled="currentNodeKey == 'null'" @click="openfj">同步</el-button>
          <el-button type="success" :disabled="currentNodeKey == 'null' || tableData.length == 0" @click="save">保存</el-button>
        </div>
        <div class="view-AerospaceCompileLineList-right-btn-right">
          <el-input placeholder="请输入内容" @keyup.enter.native="getqueryCarryingMainteOrgan('searchValue')" v-model="searchValue" class="input-with-select">
            <el-button @click="getqueryCarryingMainteOrgan('searchValue')" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </div>
      </div>

      <div class="view-AerospaceCompileLineList-right-table">
        <el-table :data="tableData" border style="width: 100%" height="calc(100vh - 420px)">
          <el-table-column prop="avmatCatalogCode" label="航材编码">
            <template slot-scope="scope">
              <i class="el-icon-edit cell-edit" @click="sparePartsCodingClick(scope.$index, scope.row)"></i>
              <span>{{ scope.row.avmatCatalogCode }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="avmatCatalogName" label="航材名称" align="center"> </el-table-column>
          <el-table-column prop="specification" label="航材型号" align="center"> </el-table-column>
          <el-table-column prop="mappingCode" label="映射编号" align="center"> </el-table-column>
          <el-table-column prop="avmatCategoriesName" label="航材分类" align="center"> </el-table-column>
          <el-table-column prop="unit" label="计量单位" align="center"> </el-table-column>
          <el-table-column prop="aircaftCatalogCode" label="指向飞机" align="center"> </el-table-column>
          <el-table-column prop="carryQuantity" label="携带数量" align="center">
            <template slot-scope="scope">
              <template v-if="scope.row.carryQuantity.value || scope.row.carryQuantity.value == ''">
                <el-input @blur="carryQuantityBlur(scope.$index, scope.row)" type="text" v-model="scope.row.carryQuantity.value" />
              </template>
              <template v-else>
                <i @click="editCarryQuantity(scope.$index, scope.row)" class="el-icon-edit cell-edit"></i>
                <span>{{ scope.row.carryQuantity }}</span>
              </template>
            </template>
          </el-table-column>
          <el-table-column prop="purchasePrice" label="单价/万元" align="center"> </el-table-column>
          <el-table-column prop="createBy" label="创建人" align="center"> </el-table-column>
          <!-- <el-table-column prop="amount" label="金额/元" align="center"> </el-table-column> -->
          <el-table-column prop="updateTime" label="更新时间" align="center"> </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button @click="handleRemoveClick(scope.$index, scope.row)" type="text" size="small">删除</el-button>
              <el-button :disabled="!!scope.row.mappingCode" @click="handleUpdateMapClick(scope.$index, scope.row)" type="text" size="small">映射编码</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        background
        :total="pagination.total"
        :page-size="pagination.pageSize"
        :page-sizes="[10, 20, 30, 40, 50]"
        layout="sizes,total, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleIndexChange"
        style="padding: 20px; text-align: center"
      >
      </el-pagination>

      <!-- 选择航材 -->
      <AviationMaterialsModal ref="AviationMaterialsModal" avmatType="0" @select="selectAviationMaterialsModal" />

      <!-- 自动生成 -->
      <el-dialog title="数量自动计算" :visible.sync="dialogVisible" width="1000px" :before-close="generationHandleClose">
        <div class="auto-generation">
          <span>计算模型</span>
          <el-select v-model="formulaValue" placeholder="请选择" @change="handleCalculation">
            <el-option v-for="item in formulaOptions" :key="item.calculationModelId" :label="item.formulaName" :value="item.calculationModelId"> </el-option>
          </el-select>
        </div>
        <div class="auto-generation">
          <span>公式展示</span>
          <MathJax ref="MathJax" :formula="formulaShow" />
        </div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="generationHandleClose">取 消</el-button>
          <el-button type="primary" @click="generationHandelClick">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 同步生成 -->
      <el-dialog title="同步生成" :visible.sync="fjdialogVisible" width="500px" :before-close="fjHandleClose">
        <div class="auto-generation">
          <span>目标飞机</span>
          <el-select ref="onSelect" v-model="fjValue" placeholder="请选择">
            <el-option hidden :value="fjValue" :label="fjName"></el-option>
            <el-tree default-expand-all :data="menuTreeData" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
          </el-select>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="fjHandleClose">取 消</el-button>
          <el-button type="primary" @click="fjHandelClick">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 导入 -->
      <ImportDialog ref="ImportDialog" @submitCallBack="ImportDialogCallBack" />

      <!-- 映射编码 -->
      <MappingCoding ref="MappingCoding" currentNodeKey="" @handleMappingCoding="handleMappingCoding" />
    </div>
  </div>
</template>

<script>
import vue from 'vue'
import { treeObj, addModeOptions } from './index'
import { useMessage } from '@/utils/element-ui'
import ImportDialog from '../importDialog/index.vue'
import MappingCoding from '../mappingCoding/index.vue'
import {
  queryFlyTaskAircraft,
  getCarryingMainteOrgan,
  batchAddCarryingMainteOrgan,
  removeCarryingMainteOrgan,
  syncCarryingMainteOrgan,
  getEnableList,
  formulaCalculateByTaskId,
  PredictAlg,
  exportExcel
} from '@/api/carrierStandard/carrierListMachineryPreparation'
export default {
  name: 'CarrierListMachineryPreparation',
  components: { ImportDialog, MappingCoding },
  data() {
    return {
      detail: null,
      taskId: this.$route.params.id,
      fjdialogVisible: false,
      fjValue: '', //
      fjName: '',
      currentNodeKey: 'null',
      flyTaskActive: '',
      menuTreeData: [],
      treeObj: treeObj,
      defaultProps: {
        children: 'flyTaskAircraftVos',
        label: 'aircaftCatalogCode'
      },
      searchValue: '',
      modelValue: '战斗机',
      modelList: [
        { label: '战斗机', value: '战斗机' },
        { label: '运输机', value: '运输机' },
        { label: '轰炸机', value: '轰炸机' }
      ],

      tableData: [],
      pagination: {
        total: 100,
        pageSize: 10,
        pageIndex: 1
      },

      activeIndex: null,

      dialogVisible: false,
      formulaValue: '',
      formulaOptions: [],
      formulaDisplay: '',
      addModeValue: '1',
      addModeOptions: addModeOptions,
      cacheList: [],
      formulaShow: null
    }
  },
  mounted() {
    this.initData()
  },
  methods: {
    async fjHandelClick() {
      let postData = {
        aircaftCatalogId: this.fjValue,
        aimAircaftCatalogId: this.currentNodeKey
      }
      const { code, data } = await syncCarryingMainteOrgan(postData)
      if (code == 200) {
        this.fjdialogVisible = false
        this.fjValue = ''
        this.fjName = ''
        useMessage('success', '同步成功', 1000)
        this.getqueryCarryingMainteOrgan()
      }
    },
    fjHandleClose() {
      this.fjValue = ''
      this.fjName = ''
      this.fjdialogVisible = false
    },
    openfj() {
      this.fjdialogVisible = true
    },
    handleNodeClick(data) {
      const { aircaftCatalogId, flyTaskAircaftId, aircaftCatalogCode } = data
      this.fjValue = flyTaskAircaftId
      this.fjName = aircaftCatalogCode
      this.$refs.onSelect.blur()
    },
    async initData() {
      let postData = {
        taskId: this.taskId
      }
      const { code, data } = await queryFlyTaskAircraft(postData)
      if (code == 200) {
        this.menuTreeData = data.flys
        this.detail = data
        this.currentNodeKey = this.menuTreeData[0].flyTaskAircaftId
        this.currentNode = this.menuTreeData[0]
        this.getqueryCarryingMainteOrgan()
        this.$store.commit('app/updataTagsItemMetaTitle', { id: this.$route.params.id, otherTitle: '携行清单机务编修-编修', newTitle: `携行清单机务编修-编修-${this.detail.taskName}` })
      }
    },

    async getqueryCarryingMainteOrgan(searchValue) {
      searchValue ? (this.pagination.pageIndex = 1) : (this.pagination.pageIndex = this.pagination.pageIndex)
      let postData = {
        pageIndex: this.pagination.pageIndex,
        pageSize: this.pagination.pageSize,
        flyTaskAircaftId: this.currentNodeKey,
        taskId: this.taskId,
        queryParam: this.searchValue,
        avmatType: '0'
      }
      const { code, data } = await getCarryingMainteOrgan(postData)
      if (code == 200) {
        this.tableData = data.list
        this.pagination.total = data.totalCount
      }
    },

    handleIndexChange(val) {
      this.pagination.pageIndex = val
      this.getqueryCarryingMainteOrgan()
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.getqueryCarryingMainteOrgan()
    },
    treeNodeClick(node) {
      this.pagination.pageIndex = 1
      this.currentNodeKey = node.flyTaskAircaftId
      this.flyTaskActive = node.aircaftCatalogCode
      this.currentNode = node
      this.getqueryCarryingMainteOrgan()
    },
    handleRemoveClick(index, row) {
      if (row.mainteOrganId) {
        this.$confirm('是否删除该航材', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            let params = {
              mainteOrganIds: [row.mainteOrganId],
              status: 2,
              taskId: this.$route.params.id
            }
            const { code, data } = await removeCarryingMainteOrgan(params)
            if (code == 200) {
              this.getqueryCarryingMainteOrgan()
              useMessage('success', '删除成功', 1000)
            }
          })
          .catch(() => {})
      } else {
        this.tableData.splice(index, 1)
        this.$message({
          type: 'success',
          message: '操作成功!'
        })
      }
    },
    carryQuantityBlur(index, row) {
      row.carryQuantity = row.carryQuantity.value
      this.tableData[index] = row
    },
    addRow() {
      let obj = {
        avmatCatalogCode: '', //编码
        avmatCatalogName: '', // 航材名称
        specification: '', // 航材型号
        avmatCategoriesName: '', // 航材分类
        unit: '',
        avmatType: 0,
        aircaftCatalogCode: this.flyTaskActive, // 指向飞机
        flyTaskAircaftId: this.currentNodeKey, // 指向飞机的ID
        avmatCatalogId: '', // 航材id
        taskId: this.taskId,
        carryQuantity: {
          // 携带数量
          value: ''
        },
        purchasePrice: '', // 价格
        updateTime: '', // 更新时间
        taskStatic: 1 // 任务状态（0非携行，1携行）
      }
      this.tableData.unshift(obj)
      this.cacheList.unshift(obj)
    },
    editCarryQuantity(index, row) {
      let value = row.carryQuantity
      row.carryQuantity = {}
      vue.set(row.carryQuantity, 'value', value)
      this.tableData[index] = row
    },
    sparePartsCodingClick(index, row) {
      this.activeIndex = index
      this.$refs.AviationMaterialsModal.openFittings()
    },
    closeStructureEquipping() {},
    dialogFetchTableData() {},

    selectAviationMaterialsModal(row) {
      for (const key in this.tableData[this.activeIndex]) {
        if (key && row[key]) {
          vue.set(this.tableData[this.activeIndex], key, row[key])
        }
        this.tableData[this.activeIndex].mappingCode = row.mappingCode
      }
      this.fittingsVisible = false
      this.activeIndex = null
    },
    async openDialogVisible() {
      const { data } = await getEnableList()
      this.formulaOptions = data
      if (data.length) {
        this.formulaValue = data[0].calculationModelId
        this.formulaShow = data[0].formulaShow
      }
      this.dialogVisible = true
    },
    handleCalculation(row) {
      const result = this.formulaOptions.find((item) => item.calculationModelId == this.formulaValue)
      if (result) {
        this.formulaShow = result.formulaShow
      }
    },
    generationHandleClose() {
      this.dialogVisible = false
    },
    async generationHandelClick() {
      if (!this.formulaValue) return useMessage('warning', '请选择计算模型', 1000)
      let params = {
        calculationModelId: this.formulaValue,
        taskId: this.taskId
      }
      await formulaCalculateByTaskId(params)
      this.getqueryCarryingMainteOrgan()
      useMessage('success', '生成成功', 1000)
      this.dialogVisible = false
    },
    async save() {
      for (let index = 0; index < this.tableData.length; index++) {
        const element = this.tableData[index]
        if (element.mappingCode == null || element.mappingCode == '') {
          useMessage('error', `第${index + 1}行数据没有映射编号`, 1000)
          return
        }
        if (element.avmatCatalogCode == '' || element.carryQuantity == '' || element.carryQuantity.value == '') {
          useMessage('error', `第${index + 1}行数据没有填写完整`, 1000)
          return
        }
      }
      let params = {
        carryingMainteOrgans: this.tableData,
        status: 3
      }
      const { code, data } = await batchAddCarryingMainteOrgan(params)
      if (code == 200) {
        useMessage('success', '保存成功', 1000)
        this.cacheList = []
        this.getqueryCarryingMainteOrgan()
      }
    },
    varietyRecommendation() {
      this.$confirm('是否确认进行品种推荐', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let params = {
            aircraftId: this.currentNodeKey,
            taskId: this.$route.params.id
          }
          const { code, data } = await PredictAlg(params)
          if (code == 200) {
            this.getqueryCarryingMainteOrgan()
            useMessage('success', '操作成功', 1000)
          }
        })
        .catch(() => {})
    },
    //导入
    importOperation() {
      let params = {
        taskId: this.$route.params.id
      }
      this.$refs.ImportDialog.triggerDialog(params)
    },
    //导入回写
    ImportDialogCallBack() {
      this.getqueryCarryingMainteOrgan()
    },
    //导出全部
    async allExport() {
      let params = {
        flyTaskAircaftId: this.currentNodeKey,
        taskId: this.taskId,
        queryParam: this.searchValue,
        avmatType: '0'
      }
      await exportExcel(params)
    },
    handleUpdateMapClick(index, row) {
      this.activeIndex = index
      // if (row.mainteOrganId) {
      this.$refs.MappingCoding.openMappingCoding(row)
      // } else {
      //   useMessage('error', '该行数据没有保存,请先保存！', 1000)
      // }
    },
    handleMappingCoding(activeRow, updateRow) {
      vue.set(this.tableData[this.activeIndex], 'mappingCode', activeRow.avmatCatalogCode)
      this.fetchTableData()
    }
  }
}
</script>

<style lang="scss">
@import './index.scss';
</style>
