<template>
  <div class="view-table-content">
    <!-- <div class="view-dataSpecies-left">
      <MenuTree :currentNodeKey="currentNodeKey" nodeKey="id" :treedata="menuTreeData" @TreeNodeclick="treeNodeClick" v-bind="treeObj"> </MenuTree>
    </div> -->
    <div style="width: 100%">
      <div class="view-dataType-title">
        <div class="view-dataType-title-btn">
          <el-button type="success" @click="openDialog()" :disabled="currentNode && currentNode.type == 0">新增</el-button>
          <el-button type="warning" @click="remove(tableCheckItems)" :disabled="tableCheckItems.length == 0">删除</el-button>
          <!-- <el-button type="primary">导入模板</el-button>
          <el-button type="primary">导出模板</el-button> -->
        </div>
        <div class="view-dataType-title-search">
          <el-input placeholder="请输入机型/HMC码" v-model="keyWord" 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="model">
            <el-select v-model="form.model" placeholder="请选择机型">
              <el-option v-for="item in aircaftModelAll" :key="item.aircaftModelId" :label="item.aircaftModelName" :value="item.aircaftModelId"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="HMC码" prop="hmcCode">
            <el-input v-model="form.hmcCode" placeholder="请输入HMC码" />
          </el-form-item>
          <el-form-item label="参数列" prop="parameterColumn">
            <el-checkbox-group v-model="form.parameterColumn">
              <div style="column-count: 3">
                <el-checkbox v-for="dict in dictData" :key="dict.dictValue" :value="dict.dictValue" :label="dict.dictLabel">{{ dict.dictLabel }}</el-checkbox>
              </div>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="模型" prop="pattern">
            <el-select v-model="form.pattern" placeholder="请选择模型">
              <el-option v-for="item in modelData.list" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </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 { getJudgeFaultLogic, getAircaftTypeAndModelTree, addJudgeFaultLogic, updateJudgeFaultLogic, removeJudgeFaultLogic } from '@/api/als/judgeFaultLogic'
import { deepClone, debounce } from '@/utils/index'
import { getDict } from '@/api/dict'
import { getModel } from '@/api/als/model'
import { getAircaftModelAll, getAircaftCatalogAll } from '@/api/als/aircraft'
export default {
  name: 'JudgeFaultLogic',
  components: {},
  data() {
    // 这里存放数据
    return {
      dialogTitle: '新增',
      dialogVisible: false,
      keyWord: '',
      aircaftModelIdList: [],
      currentNodeKey: null,
      currentNode: null,
      menuTreeData: [],
      dictData: [],
      modelData: [],
      treeObj: {
        title: '所属机种',
        activityheight: '275px',
        searchIcon: false,
        configure: {
          children: 'children',
          label: 'label'
        }
      },
      typeTree: {
        children: 'children',
        label: 'label'
      },
      searchValue: '',
      columns: [
        { prop: 'id', label: '编号' },
        {
          prop: 'model',
          label: '机型',
          render: (h, params) => {
            const matchedItem = this.aircaftModelAll.find((item) => params.row.model === item.aircaftModelId)
            if (matchedItem) {
              return h('span', matchedItem.aircaftModelName)
            } else {
              return h('span', params.row.model)
            }
          }
        },
        {
          prop: 'hmcCode',
          label: 'HMC码'
        },
        {
          prop: 'parameterColumn',
          label: '参数列'
        },
        {
          prop: 'pattern',
          label: '模型',
          render: (h, params) => {
            const matchedItem = this.modelData.list.find((item) => params.row.pattern === item.id)
            if (matchedItem) {
              return h('span', matchedItem.name)
            } else {
              return h('span', {}, '')
            }
          }
        },
        {
          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: '',
        model: '',
        hmcCode: '',
        parameterColumn: [],
        pattern: '',
        remarks: '',
        tenantId: '',
        delFlag: '',
        version: '',
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: ''
      },
      rules: {
        model: [{ required: true, message: '机型不能为空', trigger: 'blur' }],
        hmcCode: [{ required: true, message: 'HMC码不能为空', trigger: 'blur' }],
        parameterColumn: [{ required: true, message: '参数列不能为空', trigger: 'blur' }],
        pattern: [{ required: true, message: '模型不能为空', trigger: 'blur' }]
      },
      debounceFn: debounce(this.fetch, 500),
      aircaftModelAll: []
    }
  },
  watch: {
    keyWord() {
      this.tableRequset.pageIndex = 1
      this.debounceFn()
    }
  },
  mounted() {
    this.getDict()
    this.getModelAPI()
    this.getJudgeFaultLogicAPI()
    // this.getAircaftTypeAndModelTreeAPI()
  },
  methods: {
    async getDict() {
      const { data } = await getDict('als_parameter_column')
      this.dictData = data
    },

    async getModelAPI() {
      const { data } = await getModel({ pageSize: 100, pageNum: 1, ...{ type: 5 } })
      this.modelData = data
    },

    async getAircaftTypeAndModelTreeAPI(params) {
      const { data } = await getAircaftTypeAndModelTree(params)
      this.menuTreeData = data
      if (data.length) {
        this.currentNodeKey = data[0].value
        this.currentNode = data[0]
        this.aircaftModelIdList = this.getTreeLeafData(data[0]?.children).map((e) => e.id)
        this.getJudgeFaultLogicAPI()
      }
    },

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

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

    async getJudgeFaultLogicAPI(params) {
      if (this.$refs.table) this.$refs.table.clearSelection()
      const { keyWord } = this
      const { pageSize, pageIndex } = this.tableRequset
      const {
        data: { list, totalCount }
      } = await getJudgeFaultLogic({ pageSize, pageNum: pageIndex, keyWord, ...params })
      this.tableData = list
      this.tableRequset.total = totalCount
      const getAircaftModelAllParams = {
        aircaftTypeCode: '',
        aircaftTypeId: '',
        queryParam: ''
      }
      const { data: data1 } = await getAircaftModelAll(getAircaftModelAllParams)
      this.aircaftModelAll = data1
    },

    fetch() {
      this.getJudgeFaultLogicAPI()
    },

    searchClick() {
      this.getJudgeFaultLogicAPI()
    },

    async addJudgeFaultLogicAPI() {
      this.form.parameterColumn = this.form.parameterColumn.toString()
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          try {
            delete this.form.aircaftModelName
            const { code } = await addJudgeFaultLogic({ ...this.form })
            if (code === 200) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.getJudgeFaultLogicAPI()
              this.handleClose()
            }
          } catch (error) {}
        }
      })
    },

    async updateJudgeFaultLogicAPI() {
      this.form.parameterColumn = this.form.parameterColumn.toString()
      try {
        const { code } = await updateJudgeFaultLogic({ ...this.form })
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.getJudgeFaultLogicAPI()
          this.handleClose()
        }
      } catch (error) {}
    },

    treeNodeClick(data) {
      this.$refs.table.clearSelection()
      this.currentNodeKey = data.id
      this.currentNode = data
      this.aircaftModelIdList = this.getTreeLeafData(data.children.length ? data.children : [data]).map((e) => e.id)
      this.getJudgeFaultLogicAPI()
    },

    openDialog() {
      this.dialogTitle = '新增'
      this.dialogVisible = true
      // this.form.aircaftModelName = this.currentNode.label
      // this.form.aircaftModelId = this.currentNode.id
    },

    handleClose() {
      this.dialogVisible = false
      this.form = {
        id: '',
        model: '',
        hmcCode: '',
        parameterColumn: [],
        pattern: '',
        remarks: '',
        tenantId: '',
        delFlag: '',
        version: '',
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: ''
      }
    },

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

    submit() {
      switch (this.dialogTitle) {
        case '编辑':
          this.updateJudgeFaultLogicAPI()
          break
        case '新增':
          this.addJudgeFaultLogicAPI()
          break
      }
    },

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

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

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