<template>
  <div class="view-table-content">
    <div class="view-dataSpecies-left" style="display: flex; width: 430px">
      <MenuTree :currentNodeKey="currentNodeKey" nodeKey="id" :treedata="menuTreeData" @TreeNodeclick="treeNodeClick" v-bind="treeObj" style="width: 250px"> </MenuTree>
      <MenuTree :currentNodeKey="currentConfigNodeKey" nodeKey="id" :treedata="configTreeData" @TreeNodeclick="treeConfigNodeClick" v-bind="configurationTreeObj" style="width: 250px"> </MenuTree>
    </div>
    <div class="view-dataSpecies-right" style="width: calc(100% - 460px)">
      <div class="view-dataType-title">
        <div class="view-dataType-title-btn">
          <el-button type="success" @click="openDialog()" :disabled="!(currentNode.type == 2) || currentConfigNodeKey === ''">新增</el-button>
          <el-button type="warning" @click="remove(tableCheckItems)" :disabled="tableCheckItems.length == 0">删除</el-button>
        </div>
        <div class="view-dataType-title-search">
          <el-input placeholder="请输入航材名称" v-model="keyWordData" class="input1">
            <el-button slot="append" icon="el-icon-search" @click="searchClick"></el-button>
          </el-input>
        </div>
      </div>

      <div class="view-dataType-table">
        <LTable ref="table" @selection-change="selection" :defaultFetch="false" :fetch="fetch" :columns="columns" :dataSource="tableData" :options="options" :pagination="tableRequset"></LTable>
      </div>

      <!-- 添加或修改装机信息对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="1000px" :before-close="handleClose">
        <LTable ref="avmatTableRef" @current-change="avmatSelection" :showColumnSetting="false" :defaultFetch="false" :columns="avmatColumns" :dataSource="avmatTableData" :options="avmatOptions" :pagination="avmatTableRequset"></LTable>
        <el-form ref="formRef" style="margin-top: 20px" :inline="true" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="航材名称" prop="devicesName">
            <el-input v-model="form.devicesName" placeholder="请输入航材名称" disabled />
          </el-form-item>
          <el-form-item label="航材编码" prop="devicesEncode">
            <el-input v-model="form.devicesEncode" placeholder="请输入航材编码" disabled />
          </el-form-item>
          <el-form-item label="规格型号" prop="specsModel">
            <el-input disabled v-model="form.specsModel" placeholder="请输入规格型号" />
          </el-form-item>
          <el-form-item label="图号" prop="drawingNumber">
            <el-input disabled v-model="form.drawingNumber" placeholder="请输入图号" />
          </el-form-item>
          <el-form-item label="所属分类" prop="category">
            <el-input disabled v-model="form.category" placeholder="请输入所属分类" />
          </el-form-item>
          <el-form-item label="是否可修" prop="repairable">
            <el-select disabled v-model="form.repairable" placeholder="请选择是否可修">
              <el-option label="是" :value="1"></el-option>
              <el-option label="否" :value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否成套" prop="completeSet">
            <el-select v-model="form.completeSet" placeholder="请选择是否成套" disabled>
              <el-option label="是" :value="1"></el-option>
              <el-option label="否" :value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否有寿" prop="serviceLife">
            <el-select v-model="form.serviceLife" placeholder="请选择是否有寿" disabled>
              <el-option label="是" :value="1"></el-option>
              <el-option label="否" :value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="额定寿命(s)" label-width="90px" prop="ratedLife">
            <el-input-number label="额定寿命(s)" v-model="form.ratedLife" :precision="1" :step="0.5" :min="0"></el-input-number>
          </el-form-item>
          <el-form-item label="航材代码" prop="devicesCode">
            <el-input v-model="form.devicesCode" placeholder="请输入航材代码" />
          </el-form-item>
          <el-form-item label="装机数量" prop="quantity">
            <el-input v-model="form.quantity" placeholder="请输入装机数量" />
          </el-form-item>
          <el-form-item label="装机时间" prop="installTime">
            <el-date-picker v-model="form.installTime" type="date" placement="bottom-start" value-format="yyyy-MM-dd" placeholder="请选择装机时间"></el-date-picker>
          </el-form-item>
          <el-form-item label="软件版本" prop="softwareVersion">
            <el-input v-model="form.softwareVersion" placeholder="请输入软件版本" />
          </el-form-item>

          <el-form-item label="备注" prop="remarks">
            <el-input v-model="form.remarks" type="textarea" :rows="2" placeholder="请输入备注" />
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getAirInstall, addAirInstall, updateAirInstall, removeAirInstall } from '@/api/als/airInstall'
import { getAircaftCatalogTree, getAircaftTypeAndModelTree } from '@/api/als/sideTree'
import { getAircaftModelAll, getAircaftCatalogAll } from '@/api/als/aircraft'
import { getAirConfiguration } from '@/api/als/airConfiguration'
import { deepClone, debounce } from '@/utils/index'
import { handleTree, flattenTree } from '../utils/common'
import { getAvmatCatalog } from '@/api/basicData/dataSailingMaterialMaterialCoding'

export default {
  name: 'AirInstall',
  components: {},
  data() {
    // 这里存放数据
    return {
      dialogTitle: '新增',
      dialogVisible: false,
      keyWordData: '',
      aircaftConfigIdList: [],
      currentNodeKey: '',
      currentNode: {},
      currentConfigNodeKey: '',
      currentConfigNode: {},
      menuTreeData: [],
      configTreeData: [],
      treeObj: {
        title: '所属机种',
        activityheight: '275px',
        searchIcon: false,
        configure: {
          children: 'children',
          label: 'label'
        }
      },
      configurationTreeObj: {
        title: '飞机构型',
        activityheight: '275px',
        searchIcon: false,
        configure: {
          children: 'children',
          label: 'name'
        }
      },
      typeTree: {
        children: 'children',
        label: 'label'
      },
      rules: {
        devicesName: [{ required: true, message: '请在列表中选择航材数据', trigger: 'blur' }]
      },
      searchValue: '',
      columns: [
        {
          prop: 'devicesEncode',
          label: '航材编码'
        },
        {
          prop: 'devicesCode',
          label: '航材代码'
        },
        {
          prop: 'devicesName',
          label: '航材名称'
        },
        {
          prop: 'specsModel',
          label: '规格型号'
        },
        {
          prop: 'drawingNumber',
          label: '图号'
        },
        {
          prop: 'category',
          label: '所属分类'
        },
        {
          prop: 'quantity',
          label: '装机数量'
        },
        {
          prop: 'installTime',
          label: '装机时间'
        },
        {
          prop: 'softwareVersion',
          label: '软件版本'
        },
        {
          prop: 'repairable',
          label: '是否可修',
          render: (h, params) => {
            if (params.row.repairable == 1) {
              return h('span', { class: 'success-state' }, '是')
            } else {
              return h('span', { class: 'warning-state' }, '否')
            }
          }
        },
        {
          prop: 'completeSet',
          label: '是否成套',
          render: (h, params) => {
            if (params.row.completeSet == 1) {
              return h('span', { class: 'success-state' }, '是')
            } else {
              return h('span', { class: 'warning-state' }, '否')
            }
          }
        },
        {
          prop: 'serviceLife',
          label: '是否有寿',
          render: (h, params) => {
            if (params.row.serviceLife == 1) {
              return h('span', { class: 'success-state' }, '是')
            } else {
              return h('span', { class: 'warning-state' }, '否')
            }
          }
        },
        {
          prop: 'ratedLife',
          label: '额定寿命(s)'
        },
        {
          button: true,
          label: '操作',
          width: '200px',
          group: [
            {
              name: '编辑',
              type: 'text',
              round: false,
              plain: false,
              onClick: (row, index, scope) => {
                this.handUpdate(row)
              }
            },
            {
              name: '删除',
              type: 'text',
              round: false,
              plain: false,
              onClick: (row, index, scope) => {
                this.remove([row])
              }
            }
          ]
        }
      ],
      avmatColumns: [
        {
          prop: 'avmatCatalogName',
          label: '航材名称',
          align: 'left'
        },
        {
          prop: 'avmatCatalogCode',
          label: '航材编码'
        },
        {
          prop: 'avmatCategoriesName',
          label: '所属分类'
        },
        {
          prop: 'specification',
          label: '规格型号'
        },
        {
          prop: 'diagramNumber',
          label: '图号'
        },
        {
          prop: 'unit',
          label: '计量单位'
        },
        {
          prop: 'specialty',
          label: '专业'
        },
        {
          prop: 'manufacturer',
          label: '生产厂家'
        },
        {
          prop: 'isRepairable',
          label: '是否可修',
          render: (h, params) => {
            if (params.row.status == 1) {
              return h('span', { class: 'success-state' }, '是')
            } else {
              return h('span', { class: 'warning-state' }, '否')
            }
          }
        },
        {
          prop: 'isCompleteSet',
          label: '是否成套',
          render: (h, params) => {
            if (params.row.isCompleteSet == 1) {
              return h('span', { class: 'success-state' }, '是')
            } else {
              return h('span', { class: 'warning-state' }, '否')
            }
          }
        },
        {
          prop: 'isOrdered',
          label: '是否有寿',
          render: (h, params) => {
            if (params.row.isOrdered == 1) {
              return h('span', { class: 'success-state' }, '是')
            } else {
              return h('span', { class: 'warning-state' }, '否')
            }
          }
        },
        {
          prop: 'isImported',
          label: '是否进口',
          render: (h, params) => {
            if (params.row.isImported == 1) {
              return h('span', { class: 'theme-state' }, '进口')
            } else {
              return h('span', { class: 'success-state' }, '国产')
            }
          }
        }
      ],
      options: {
        stripe: false, // 斑马纹
        mutiSelect: false, // 多选框
        index: true, // 显示序号， 多选则 mutiSelect
        loading: false, // 表格动画
        initTable: false, // 是否一挂载就加载数据
        border: true,
        height: 'calc(100vh - 300px)'
      },
      avmatOptions: {
        stripe: false, // 斑马纹
        mutiSelect: false, // 多选框
        index: true, // 显示序号， 多选则 mutiSelect
        loading: false, // 表格动画
        initTable: false, // 是否一挂载就加载数据
        border: true,
        height: '300px'
      },
      tableCheckItems: [],
      tableData: [],
      avmatTableData: [],
      tableRequset: {
        total: 0,
        pageIndex: 1,
        pageSize: 20,
        searchValue: ''
      },
      avmatTableRequset: {
        total: 0,
        pageIndex: 1,
        pageSize: 20,
        searchValue: ''
      },
      form: {
        id: '',
        airId: '', //编目id
        airModelId: '', //机号id
        configId: '', //构型id
        devicesEncode: '',
        devicesCode: '',
        devicesName: '',
        specsModel: '',
        drawingNumber: '',
        category: '',
        quantity: '',
        installTime: '',
        softwareVersion: '',
        repairable: '',
        completeSet: '',
        serviceLife: '',
        ratedLife: '',
        remarks: ''
      },
      debounceFn: debounce(this.fetch, 500),
      currentAirId: '',
      currentAirModelId: '',
      configNodeIdList: []
    }
  },
  watch: {
    keyWord() {
      this.tableRequset.pageIndex = 1
      this.debounceFn()
    }
  },
  mounted() {
    this.getAircaftCatalogTreeAPI()
  },
  methods: {
    async getAircaftCatalogTreeAPI(params) {
      const { data } = await getAircaftCatalogTree(params)
      this.menuTreeData = data
      const { pageSize, pageIndex } = this.avmatTableRequset
      const {
        data: { list, totalCount }
      } = await getAvmatCatalog({
        pageIndex,
        pageSize,
        avmatCategoriesId: '',
        avmatType: '1'
      })
      this.avmatTableData = flattenTree(list)
      this.avmatTableRequset.total = totalCount
      // if (data.length) {
      //   this.currentNodeKey = data[0].id
      //   this.currentNode = data[0]
      //   this.getAirInstallAPI()
      // }
    },

    async removeAirInstallAPI(params) {
      try {
        const { code } = await removeAirInstall(params)
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          await this.getAirInstallAPI({ configId: this.currentConfigNodeKey })
          this.handleClose()
        }
      } catch (error) {}
    },

    getTreeLeafData(list) {
      const newArr = []
      function getLeaf(data, arr) {
        data.forEach((e) => {
          if (e.type === 2) {
            arr.push(e)
          }
          if (e.children.length) {
            getLeaf(e.children, arr)
          }
        })
      }
      getLeaf(list, newArr)
      return newArr
    },

    getAllTreeData(list) {
      const newArr = []
      function getLeaf(data, arr) {
        data.forEach((e) => {
          if (e.children && e.children.length) {
            getLeaf(e.children, arr)
          } else {
            arr.push(e)
          }
        })
      }
      getLeaf(list, newArr)
      return newArr
    },

    async getAirInstallAPI(params) {
      if (this.$refs.table) this.$refs.table.clearSelection()
      const { pageSize, pageIndex } = this.tableRequset
      const {
        data: { list, total }
      } = await getAirInstall({ pageSize, pageNum: pageIndex, ...params })
      this.tableData = list
      this.tableRequset.total = total
    },

    fetch() {
      this.getAirInstallAPI({ configId: this.currentConfigNodeKey })
    },

    searchClick() {
      this.getAirInstallAPI({ configId: this.currentConfigNodeKey, devicesName: this.keyWordData })
    },

    async addAirInstallAPI() {
      try {
        delete this.form.aircaftModelName
        const { code } = await addAirInstall({ ...this.form })
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.handleClose()
          this.getAirInstallAPI({ configId: this.currentConfigNodeKey })
        }
      } catch (error) {}
    },

    async updateAirInstallAPI() {
      try {
        const { code } = await updateAirInstall({ ...this.form })
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.handleClose()
          this.getAirInstallAPI({ configId: this.currentConfigNodeKey })
        }
      } catch (error) {}
    },

    async treeNodeClick(data) {
      // this.$refs.table.clearSelection()
      this.currentAirId = this.form.airId = data.id
      this.currentAirModelId = this.form.airModelId = data.parentId
      this.currentNode = data
      // this.getAirInstallAPI(this.currentNodeKey)
      let dataTree = []
      if (data.type === 1) {
        const { data: data1 } = await getAirConfiguration({ aircraftType: data.id })
        dataTree = data1
      } else if (data.type === 2) {
        const { data: data1 } = await getAirConfiguration({ aircraftType: data.parentId })
        dataTree = data1
      }
      this.configTreeData = []
      const topNode = { id: 1, name: '整机', children: [] }
      // topNode.children = data1
      topNode.children = handleTree(dataTree, 'id')
      this.configTreeData.push(topNode)
    },

    treeConfigNodeClick(data) {
      this.$refs.table.clearSelection()
      this.currentConfigNodeKey = this.form.configId = data.id
      this.currentConfigNode = data
      // const dataTree = this.configTreeData
      // console.log('dataTree', dataTree)
      // this.configNodeIdList = String(this.getAllTreeData(dataTree[0].children.length ? dataTree[0].children : [dataTree[0]]).map((e) => e.id))
      // console.log('this.configNodeIdList', this.configNodeIdList)
      // this.getAirInstallAPI({ configId: this.configNodeIdList })
      this.getAirInstallAPI({ configId: this.currentConfigNodeKey })
    },

    openDialog() {
      this.dialogTitle = '新增'
      this.dialogVisible = true
      this.form.configId = this.currentConfigNodeKey
      this.form.airId = this.currentAirId
      this.form.airModelId = this.currentAirModelId
    },

    handleClose() {
      this.$refs.avmatTableRef.clearSelection()
      this.dialogVisible = false
      this.form = {
        id: '',
        airId: '', //编目id
        airModelId: '', //机型id
        configId: '', //构型id
        devicesEncode: '',
        devicesCode: '',
        devicesName: '',
        specsModel: '',
        drawingNumber: '',
        category: '',
        quantity: '',
        installTime: '',
        softwareVersion: '',
        repairable: '',
        completeSet: '',
        serviceLife: '',
        ratedLife: '',
        remarks: ''
      }
    },

    handUpdate(row) {
      this.dialogTitle = '编辑'
      this.form = deepClone(row)
      this.dialogVisible = true
    },

    submit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          switch (this.dialogTitle) {
            case '编辑':
              this.updateAirInstallAPI()
              break
            case '新增':
              this.addAirInstallAPI()
              break
          }
        }
      })
    },

    selection(val) {
      this.tableCheckItems = val
    },

    avmatSelection(val) {
      this.form.devicesName = val.avmatCatalogName
      this.form.devicesEncode = val.avmatCatalogCode
      this.form.category = val.avmatCategoriesName
      this.form.specsModel = val.specification
      this.form.drawingNumber = val.diagramNumber
      this.form.repairable = val.isRepairable
      this.form.completeSet = val.isCompleteSet
      this.form.serviceLife = val.isOrdered
    },

    remove(row) {
      this.$confirm('是否删除该数据', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.removeAirInstallAPI(row.map((e) => e.id))
        })
        .catch(() => {})
    },

    async changeDevicesName(avmatCatalogId) {
      const {
        data: { list }
      } = await getAvmatCatalog({
        avmatCatalogId: avmatCatalogId
      })
      // this.form = list[0]
      // console.log(this.form, list[0])
    }
  }
}
</script>

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