<template>
  <div class="view-table-content">
    <div style="width: 100%">
      <div class="view-dataType-title">
        <div class="view-dataType-title-btn">
          <el-button type="success" @click="openDialog()">新增</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="600px" :before-close="handleClose">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="模型名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入模型名称" />
          </el-form-item>
          <el-form-item label="模型类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择模型类型">
              <el-option v-for="item in $enumData.agloModelList" :key="item.key" :label="item.name" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item label="模型链接" prop="url">
            <el-input v-model="form.url" placeholder="请输入模型链接" />
          </el-form-item>
          <el-form-item v-show="['5', '6'].includes(form.type)" label="机型" prop="aircraftType">
            <treeselect :value="form.aircraftType" :normalizer="aircraftTypeNormalizer" :options="aircraftTypeTreeData" :show-count="true" placeholder="请选择机型" @select="aircraftTypeChange" />
          </el-form-item>
          <el-form-item v-show="['5', '6'].includes(form.type)" label="部件" prop="partId">
            <treeselect :value="form.partId" :normalizer="normalizer" :options="partsData" :show-count="true" placeholder="请选择部件" @select="partIdSelect" />
            <!-- <el-select v-model="form.partId" filterable placeholder="请选择部件">
              <el-option v-for="item in partsData" :key="item.id" :label="item.devicesName" :value="item.id"> </el-option>
            </el-select> -->
          </el-form-item>
          <el-form-item label="参数" prop="param">
            <el-input type="textarea" :rows="2" v-model="form.param" placeholder="请输入参数" />
          </el-form-item>
          <el-form-item label="数据列" prop="columnData">
            <el-input type="textarea" :rows="3" v-model="form.columnData" placeholder="请输入数据列" />
          </el-form-item>
          <el-form-item v-if="dialogTitle === '编辑'" label="状态" prop="status">
            <el-switch v-model="form.status" active-color="#13ce66" active-value="1" inactive-value="0"> </el-switch>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" :rows="2" v-model="form.remark" 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 { getModel, addModel, updateModel, removeModel } from '@/api/als/model'
import { deepClone, debounce } from '@/utils/index'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { handleTree } from '../utils/common'
import { agloModelList } from '@/views/als/utils/enum-data'
import { getAirConfiguration } from '@/api/als/airConfiguration'
import { getAirInstall } from '@/api/als/airInstall'
import { getAircaftTypeAndModelTree } from '@/api/als/sideTree'

export default {
  name: 'Model',
  components: { Treeselect },
  data() {
    // 这里存放数据
    return {
      dialogTitle: '新增',
      dialogVisible: false,
      keyWordData: '',
      aircaftModelIdList: [],
      searchValue: '',
      columns: [
        {
          prop: 'name',
          label: '模型名称'
        },
        {
          prop: 'type',
          label: '模型类型',
          render: (h, params) => {
            const matchedItem = this.$enumData.agloModelList.find((item) => params.row.type === item.key)
            if (matchedItem) {
              return h('span', matchedItem.name)
            } else {
              return h('span', {}, '')
            }
          }
        },
        {
          prop: 'url',
          label: '模型链接'
        },
        {
          prop: 'partId',
          label: '部件',
          render: (h, params) => {
            const matchedItem = this.allAirConfig.find((item) => params.row.partId === item.id)
            if (matchedItem) {
              return h('span', matchedItem.name)
            } else {
              return h('span', {}, '')
            }
          }
        },
        {
          prop: 'param',
          label: '参数'
        },
        {
          prop: 'columnData',
          label: '数据列'
        },
        {
          prop: 'status',
          label: '状态',
          render: (h, params) => {
            if (params.row.status == 0) {
              return h('span', { class: 'warning-state' }, '禁用')
            } else {
              return h('span', { class: 'success-state' }, '启用')
            }
          }
        },
        {
          prop: 'remark',
          label: '备注'
        },
        {
          button: true,
          label: '操作',
          width: '240px',
          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])
              }
            }
          ]
        }
      ],
      options: {
        stripe: true, // 斑马纹
        mutiSelect: true, // 多选框
        index: false, // 显示序号， 多选则 mutiSelect
        loading: false, // 表格动画
        initTable: false, // 是否一挂载就加载数据
        border: true,
        height: 'calc(100vh - 300px)'
      },
      tableCheckItems: [],
      tableData: [],
      tableRequset: {
        total: 0,
        pageIndex: 1,
        pageSize: 10,
        searchValue: ''
      },
      form: {
        id: '',
        name: '',
        type: '',
        url: '',
        aircraftType: null,
        partId: null,
        param: '',
        columnData: '',
        status: '1',
        remark: ''
      },
      debounceFn: debounce(this.fetch, 500),
      partsData: [],
      aircraftTypeTreeData: [],
      allAirConfig: []
    }
  },
  watch: {
    keyWord() {
      this.tableRequset.pageIndex = 1
      this.debounceFn()
    }
  },
  mounted() {
    this.getModelAPI()
    this.getPartData()
  },
  methods: {
    async getPartData() {
      try {
        const { data } = await getAircaftTypeAndModelTree()
        const { data: airConfigData } = await getAirConfiguration()
        this.allAirConfig = airConfigData
        this.aircraftTypeTreeData = data[0].children
        console.log('this.aircraftTypeTreeData', this.aircraftTypeTreeData)
      } catch (error) {}
    },

    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },

    aircraftTypeNormalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.label,
        children: node.children
      }
    },

    aircraftTypeChange(node) {
      this.form.aircraftType = node.id
      this.getAirConfigurationAPI({ aircraftType: this.form.aircraftType })
    },

    async getAirConfigurationAPI(params) {
      try {
        const { data } = await getAirConfiguration(params)
        const treeData = handleTree(data, 'id')
        this.partsData = treeData
      } catch (error) {}
    },

    partIdSelect(node) {
      console.log('node', node)
      this.form.partId = node.id
    },

    async removeModelAPI(params) {
      try {
        const { code } = await removeModel(params)
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          await this.getModelAPI()
          this.handleClose()
        }
      } catch (error) {}
    },

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

    fetch() {
      this.getModelAPI()
    },

    async searchClick() {
      this.getModelAPI({ name: keyWordData })
    },

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

    async updateModelAPI() {
      try {
        const { code } = await updateModel({ ...this.form })
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.handleClose()
          this.getModelAPI()
        }
      } catch (error) {}
    },

    openDialog() {
      this.dialogTitle = '新增'
      this.dialogVisible = true
    },

    handleClose() {
      this.dialogVisible = false
      this.form = {
        id: '',
        name: '',
        type: '',
        url: '',
        aircraftType: null,
        partId: null,
        param: '',
        columnData: '',
        status: '1',
        remark: ''
      }
    },

    handUpdate(row) {
      this.dialogTitle = '编辑'
      this.form = deepClone(row)
      console.log('this.form', this.form)
      if (['5', '6'].includes(this.form.type)) {
        const item = this.allAirConfig.find((item) => item.id === this.form.partId)
        this.form.aircraftType = item.aircraftType
        this.getAirConfigurationAPI({ aircraftType: this.form.aircraftType })
      }

      this.dialogVisible = true
    },

    submit() {
      switch (this.dialogTitle) {
        case '编辑':
          this.updateModelAPI()

          break
        case '新增':
          this.addModelAPI()
          break
      }
    },

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

    remove(row) {
      this.$confirm('是否删除该模型', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.removeModelAPI(row.map((e) => e.id))
        })
        .catch(() => {})
    }
  }
}
</script>

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