<template>
  <div class="view-sailingMaterial">
    <div class="view-sailingMaterial">
      <!-- 通用代码 左侧按钮 右侧输入框 下拉框 -->
      <MissionDetail :detail="detail" />

      <div class="view-common-header">
        <div class="view-common-header-left">
          <el-button type="success" @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="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-dataType-table">
        <el-table :data="tableData" border style="width: 100%" height="calc(100vh - 420px)">
          <el-table-column prop="avmatCatalogName" label="航材名称" align="center">
            <template slot-scope="scope">
              <i class="el-icon-edit cell-edit" @click="sparePartsNameCodingClick(scope.$index, scope.row)"></i>
              <span>{{ scope.row.avmatCatalogName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="avmatCatalogCode" label="航材编码" align="center"> </el-table-column>
          <el-table-column prop="specification" label="规格型号" align="center"> </el-table-column>
          <el-table-column prop="avmatCategoriesName" 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"> </el-table-column>
          <el-table-column prop="purchasePrice" label="单价（元）" align="center"> </el-table-column>
          <el-table-column prop="applyForNum" label="申请总数量" align="center">
            <template slot-scope="scope">
              <template v-if="scope.row.applyForNum.value || scope.row.applyForNum.value == ''">
                <el-input @blur="cellBlue(scope.$index, scope.row, 'applyForNum')" type="text" v-model="scope.row.applyForNum.value" />
              </template>
              <template v-else>
                <i @click="editCell(scope.$index, scope.row, 'applyForNum')" class="el-icon-edit cell-edit"></i>
                <span>{{ scope.row.applyForNum }}</span>
              </template>
            </template>
          </el-table-column>
          <el-table-column prop="stockRemovalNum" label="出库总数量" align="center">
            <template slot-scope="scope">
              <template v-if="scope.row.stockRemovalNum.value || scope.row.stockRemovalNum.value == ''">
                <el-input @blur="cellBlue(scope.$index, scope.row, 'stockRemovalNum')" type="text" v-model="scope.row.stockRemovalNum.value" />
              </template>
              <template v-else>
                <i @click="editCell(scope.$index, scope.row, 'stockRemovalNum')" class="el-icon-edit cell-edit"></i>
                <span>{{ scope.row.stockRemovalNum }}</span>
              </template>
            </template>
          </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>
            </template>
          </el-table-column>
        </el-table>
        <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>
      </div>
    </div>

    <!-- 切换航材/机务 -->
    <AviationMaterialsModal ref="AviationMaterialsModal" avmatType="1" @select="selectAviationMaterialsModal" />
    <!-- 导入 -->
    <ImportDialog ref="ImportDialog" @submitCallBack="ImportDialogCallBack" />
  </div>
</template>

<script>
import vue from 'vue'
import { useMessage } from '@/utils/element-ui'
import ImportDialog from '../importDialog/index.vue'
import { queryFlyTaskAircraft, queryCarryingMainteOrgan, batchAddCarryingMainteOrgan, removeCarryingMainteOrgan, exportUseRegisterExcel } from '@/api/carrierStandard/carrierListMachineryPreparation'

export default {
  name: 'SailingMaterial',
  components: { ImportDialog },
  data() {
    // 这里存放数据
    return {
      detail: null,
      searchValue: '',
      activeIndex: null,
      currentNodeKey: '',
      pagination: {
        total: 0,
        pageIndex: 1,
        pageSize: 10,
        searchValue: ''
      },
      tableData: []
    }
  },
  mounted() {
    this.initData()
  },
  methods: {
    async initData() {
      let postData = {
        taskId: this.$route.params.id
      }
      const { code, data } = await queryFlyTaskAircraft(postData)
      if (code == 200) {
        this.detail = data
        this.fetchTableData()
        this.$store.commit('app/updataTagsItemMetaTitle', { id: this.$route.params.id, otherTitle: '携行航材使用登记-航材', newTitle: `携行航材使用登记-航材-${this.detail.taskName}` })
      }
    },
    async fetchTableData(search) {
      let postData = {
        pageSize: this.pagination.pageSize,
        pageIndex: search ? 1 : this.pagination.pageIndex,
        taskId: this.$route.params.id,
        queryParam: this.searchValue
      }
      const { code, data } = await queryCarryingMainteOrgan(postData)
      if (code == 200) {
        data.list.forEach((item) => {
          item.applyForNum = item.applyForNum ? item.applyForNum : ''
          item.stockRemovalNum = item.stockRemovalNum ? item.stockRemovalNum : ''
        })
        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()
    },
    sparePartsNameCodingClick(index, row) {
      this.activeIndex = index
      this.$refs.AviationMaterialsModal.openFittings()
    },

    addRow() {
      let obj = {
        avmatCatalogName: '',
        avmatCatalogCode: '',
        avmatCategoriesName: '',
        carryQuantity: '',
        purchasePrice: '',
        carryQuantity: 0,
        applyForNum: {
          value: ''
        },
        avmatType: 1,
        avmatCatalogId: '',
        stockRemovalNum: {
          value: ''
        },
        taskId: this.$route.params.id,
        taskStatic: 0
      }
      this.tableData.unshift(obj)
    },

    cellBlue(index, row, key) {
      row[key] = row[key].value
      this.tableData[index] = row
    },
    editCell(index, row, key) {
      let value = row[key]
      row[key] = {}
      vue.set(row[key], 'value', value)
      this.tableData[index] = row
    },
    handleRemoveClick(index, row) {
      if (row.mainteOrganId) {
        this.$confirm('是否删除该航材', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            let params = {
              mainteOrganIds: [row.mainteOrganId],
              status: '9',
              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: '操作成功!'
        })
      }
    },
    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
    },
    async save() {
      for (let index = 0; index < this.tableData.length; index++) {
        const element = this.tableData[index]
        if (element.applyForNum == '' || element.stockRemovalNum == '') {
          useMessage('error', `第${index + 1}行数据没有填写完整`, 1000)
          return
        }
      }
      let params = {
        carryingMainteOrgans: this.tableData,
        status: 10
      }
      const { code, data } = await batchAddCarryingMainteOrgan(params)
      if (code == 200) {
        useMessage('success', '保存成功', 1000)
        this.fetchTableData()
      }
    },
    //导入
    importOperation() {
      let params = {
        taskId: this.$route.params.id
      }
      this.$refs.ImportDialog.triggerDialog(params)
    },
    //导入回写
    ImportDialogCallBack() {
      this.fetchTableData()
    },
    //导出全部
    async allExport() {
      let params = {
        queryParam: this.searchValue,
        taskId: this.$route.params.id
      }
      await exportUseRegisterExcel(params)
    }
  }
}
</script>

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