<template>
  <div class="view-CarrierListMachineryPreparation-s">
    <div class="view-AerospaceCompileLineList-right-summarizing">
      <!-- 通用代码 左侧按钮 右侧输入框 下拉框 -->
      <div class="view-common-header">
        <div class="view-common-header-left">
          <!-- <el-button type="primary" @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" @click="selfMotionMapCode">自动映射编码</el-button>
          <el-button type="success" @click="save">保存</el-button>
        </div>
        <div class="view-common-header-right">
          <el-input @keyup.enter.native="fetchTableData('search')" placeholder="请输入内容" v-model="searchValue" class="input-select">
            <el-button @click="fetchTableData('search')" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </div>
      </div>

      <div class="view-AerospaceCompileLineList-right-summarizing-table">
        <el-table :data="tableData" border style="width: 100%" height="calc(100vh - 460px)">
          <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" width="180px"> </el-table-column>
          <el-table-column prop="specification" label="航材型号（机务）" align="center" width="180px"> </el-table-column>
          <el-table-column prop="mappingCode" label="航材编码（机务）" align="center" width="180px"> </el-table-column>
          <el-table-column prop="aircaftCatalogCode" label="所属飞机" align="center"> </el-table-column>
          <el-table-column prop="unit" 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="updateTime" label="更新时间" align="center"> </el-table-column>

          <el-table-column label="操作" align="center" width="160px">
            <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="1" @select="selectAviationMaterialsModal" />

      <!-- 映射编码 -->
      <MappingCoding ref="MappingCoding" currentNodeKey="" @handleMappingCoding="handleMappingCoding" />
      <!-- 导入 -->
      <ImportDialog ref="ImportDialog" @submitCallBack="ImportDialogCallBack" />
    </div>
  </div>
</template>

<script>
import vue from 'vue'
import MappingCoding from '../mappingCoding/index.vue'
import ImportDialog from '../importDialog/index.vue'
import { autoMapping } from '@/api/task/carrierFlightMission'
import { getCarryingMainteOrgan } from '@/api/carrierStandard/carrierListMachineryPreparation'
import { useMessage } from '@/utils/element-ui'
import { removeCarryingMainteOrgan, batchAddCarryingMainteOrgan, exportExcel } from '@/api/carrierStandard/carrierListMachineryPreparation'
export default {
  name: 'CarrierSummarizing',
  components: { MappingCoding, ImportDialog },
  data() {
    // 这里存放数据
    return {
      currentNodeKey: '',
      searchValue: '',
      tableData: [],
      pagination: {
        total: 0,
        pageSize: 10,
        pageIndex: 1
      },

      activeIndex: null
    }
  },
  mounted() {
    this.fetchTableData()
  },
  methods: {
    async fetchTableData(search) {
      let postData = {
        pageSize: this.pagination.pageSize,
        pageIndex: search ? 1 : this.pagination.pageIndex,
        taskId: this.$route.params.id,
        queryParam: this.searchValue,
        avmatType: '1'
      }
      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.fetchTableData()
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchTableData()
    },
    handleRemoveClick(index, row) {
      if (row.mainteOrganId) {
        this.$confirm('是否删除该航材', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            let params = {
              mainteOrganIds: [row.mainteOrganId],
              status: '5',
              taskId: this.$route.params.id
            }
            const { code, data } = await removeCarryingMainteOrgan(params)
            if (code == 200) {
              this.fetchTableData()
              useMessage('success', '删除成功', 1000)
            }
          })
          .catch(() => {})
      } else {
        this.tableData.splice(index, 1)
        this.$message({
          type: 'success',
          message: '操作成功!'
        })
      }
    },
    selfMotionMapCode() {
      this.$confirm('是否自动映射所有编码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { code, data } = await autoMapping()
          if (code == 200) {
            this.fetchTableData()
            useMessage('success', '映射成功', 1000)
          }
        })
        .catch(() => {})
    },
    carryQuantityBlur(index, row) {
      row.carryQuantity = row.carryQuantity.value
      this.tableData[index] = row
    },
    addRow() {
      let obj = {
        avmatCatalogCode: '',
        avmatCatalogName: '',
        specification: '',
        mappingCode: '',
        unit: '',
        avmatType: 1,
        avmatCatalogId: '',
        carryQuantity: {
          value: ''
        },
        purchasePrice: '',
        updateTime: '',
        taskStatic: 1,
        taskId: this.$route.params.id
      }
      this.tableData.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()
    },
    openDialogVisible() {
      this.$refs.AutomaticGeneration.openGenerationDialog()
    },
    generationHandelClick(data) {
      console.log(data)
    },
    handleUpdateMapClick(index, row) {
      if (row.mainteOrganId) {
        this.$refs.MappingCoding.openMappingCoding(row)
      } else {
        useMessage('error', '该行数据没有保存,请先保存！', 1000)
      }
    },
    selectAviationMaterialsModal(row) {
      for (const key in this.tableData[this.activeIndex]) {
        if (key && row[key]) {
          vue.set(this.tableData[this.activeIndex], key, row[key])
        }
      }
      this.activeIndex = null
    },
    handleMappingCoding(activeRow) {
      this.fetchTableData()
    },
    async save() {
      for (let index = 0; index < this.tableData.length; index++) {
        const element = this.tableData[index]
        if (element.avmatCatalogCode == '' || element.carryQuantity == '') {
          useMessage('error', `第${index + 1}行数据没有填写完整`, 1000)
          return
        }
      }
      let params = {
        carryingMainteOrgans: this.tableData,
        status: 6
      }
      const { code, data } = await batchAddCarryingMainteOrgan(params)
      if (code == 200) {
        useMessage('success', '保存成功', 1000)
        this.fetchTableData()
      }
    },
    //导出全部
    async allExport() {
      let params = {
        flyTaskAircaftId: null,
        taskId: this.$route.params.id,
        queryParam: this.searchValue,
        avmatType: '1'
      }
      await exportExcel(params)
    },
    //导入
    importOperation() {
      let params = {
        taskId: this.$route.params.id
      }
      this.$refs.ImportDialog.triggerDialog(params)
    },
    //导入回写
    ImportDialogCallBack() {
      this.fetchTableData()
    }
  }
}
</script>

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