<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" :rules="rules" 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'].includes(form.type)" label="参数特征" prop="paramType">
            <el-select v-model="form.paramType" filterable allow-create default-first-option placeholder="请选择参数特征">
              <el-option v-for="item in paramTypeData" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"> </el-option>
            </el-select>
          </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 noOptionsText="该机型暂无构型信息，请在构型管理中添加" :value="form.partId" :normalizer="normalizer" :options="partsData" :show-count="true" placeholder="请选择部件" @select="partIdSelect" />
          </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 { getAirConfiguration } from '@/api/als/airConfiguration'
import { getAircaftTypeAndModelTree } from '@/api/als/sideTree'
import { getDict } from '@/api/dict'
import { addData } from '@/api/system/dict/data'
import { getAircaftModelAll } from '@/api/als/aircraft'

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: 'paramType',
          label: '参数特征'
        },
        {
          prop: 'aircraftType',
          label: '机型',
          render: (h, params) => {
            const matchedItem = this.aircaftModelAll.find((item) => params.row.aircraftType === item.aircaftModelId)
            if (matchedItem) {
              return h('span', matchedItem.aircaftModelName)
            } else {
              return h('span', {}, '')
            }
          }
        },
        {
          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: 20,
        searchValue: ''
      },
      form: {
        id: '',
        name: '',
        type: '',
        url: '',
        paramType: null,
        aircraftType: null,
        partId: null,
        param: '',
        columnData: '',
        status: '1',
        remark: ''
      },
      debounceFn: debounce(this.fetch, 500),
      partsData: [],
      aircraftTypeTreeData: [],
      allAirConfig: [],
      rules: {
        name: [{ required: true, message: '模型名称不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '模型类型不能为空', trigger: 'change' }],
        url: [{ required: true, message: '模型链接不能为空', trigger: 'blur' }],
        paramType: [{ required: true, message: '参数特征不能为空', trigger: 'change' }],
        aircraftType: [{ required: true, message: '机型不能为空', trigger: 'change' }],
        partId: [{ required: true, message: '部件不能为空', trigger: 'change' }]
      },
      paramTypeData: [],
      aircaftModelAll: []
    }
  },
  watch: {
    keyWord() {
      this.tableRequset.pageIndex = 1
      this.debounceFn()
    }
  },
  mounted() {
    this.getDict()
    this.getModelAPI()
    this.getPartData()
  },
  methods: {
    async getDict() {
      const { data } = await getDict('als_model_params_character')
      this.paramTypeData = data
      const getAircaftModelAllParams = {
        aircaftTypeCode: '',
        aircaftTypeId: '',
        queryParam: ''
      }
      const { data: data1 } = await getAircaftModelAll(getAircaftModelAllParams)
      this.aircaftModelAll = data1
    },
    async getPartData() {
      try {
        const { data } = await getAircaftTypeAndModelTree()
        const { data: airConfigData } = await getAirConfiguration()
        this.allAirConfig = airConfigData
        this.aircraftTypeTreeData = data[0].children
      } 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.form.partId = null
      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) {
      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 { 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: this.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: '',
        paramType: null,
        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() {
      console.log('this.form.paramType', this.form.paramType)
      const isExist = this.paramTypeData.find((item) => {
        return item.dictLabel === this.form.paramType
      })
      if (!isExist) {
        const sortData = Math.max.apply(
          Math,
          this.paramTypeData.map((item) => {
            return item.dictSort
          })
        )
        const data = {
          dictType: 'als_model_params_character',
          dictLabel: this.form.paramType,
          dictValue: this.form.paramType,
          dictSort: sortData + 1,
          status: '0'
        }
        addData(data).then((response) => {
          if (response.code !== 200) {
            this.$message({
              type: 'warning',
              message: '模型参数特征未保存成功'
            })
            // useMessage('warning', '模型参数特征未保存成功')
          }
        })
      }

      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>
