<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="currentConfigNodeKey === '' || currentConfigNodeKey === '1'">新增</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">
        <el-table :data="tableData" class="table" @selection-change="selection">
          <el-table-column type="selection" width="55" align="center"> </el-table-column>
          <el-table-column prop="model" width="250" align="center" label="机型">
            <template slot-scope="scope">{{ changeModel(scope.row.model) }} </template>
          </el-table-column>
          <el-table-column prop="hmcCode" width="250" align="center" label="HMC码"> </el-table-column>
          <el-table-column prop="formula" label="公式" align="center">
            <template slot-scope="scope">
              <span><MathJax ref="MathJax" :formula="handleConvertFormula(scope.row.model, scope.row.formula)" /></span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="300">
            <template slot-scope="scope">
              <el-button :disabled="scope.row.isEdit == 0" @click="handUpdate(scope.row)" type="text" size="small">编辑</el-button>
              <el-button :disabled="scope.row.isEdit == 0" @click="remove(scope.row)" type="text" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          :total="tableRequset.total"
          :page-size="tableRequset.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>
      <!-- 添加或修改判故逻辑对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%" :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-col :span="24">
            <el-form-item label="公式">
              <MathJax ref="MathJax" :formula="form.formula" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="参数">
              <el-button @click="addParams(item)" type="primary" v-for="(item, index) in paramsList" :key="index">{{ item }}</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="数字">
              <el-button @click="addNumber(item)" type="primary" v-for="(item, index) in numberList" :key="index">{{ item }}</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="运算符">
              <el-button @click="addSymbol(item)" type="primary" v-for="(item, index) in operatorList" :key="index">{{ item }}</el-button>
            </el-form-item>
          </el-col>
        </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 { getAirConfigParams } from '@/api/als/airConfigParams'
import { deepClone, debounce } from '@/utils/index'
import { getDict } from '@/api/dict'
import { getModel } from '@/api/als/model'
import { getAircaftModelAll, getAircaftCatalogAll } from '@/api/als/aircraft'
import { useMessage } from '@/utils/element-ui'

export default {
  name: 'JudgeFaultLogic',
  components: {},
  data() {
    // 这里存放数据
    return {
      dialogTitle: '新增',
      dialogVisible: false,
      keyWord: '',
      aircaftModelIdList: [],
      currentNodeKey: '',
      currentNode: {},
      currentConfigNodeKey: '',
      menuTreeData: [],
      configTreeData: [],
      modelData: [],
      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'
      },
      searchValue: '',
      tableCheckItems: [],
      tableData: [],
      tableRequset: {
        total: 0,
        pageIndex: 1,
        pageSize: 20,
        searchValue: ''
      },
      form: {
        id: '',
        model: '',
        hmcCode: '',
        formula: ''
      },
      rules: {
        // model: [{ required: true, message: '机型不能为空', trigger: 'change' }],
        // hmcCode: [{ required: true, message: 'HMC码不能为空', trigger: 'blur' }],
        // parameterColumn: [{ required: true, message: '参数列不能为空', trigger: 'change' }]
      },
      debounceFn: debounce(this.fetch, 500),
      aircaftModelAll: [],
      allAirConfig: [],
      btnList: [],
      operatorList: ['+', '-', '*', '/', '>', '<', '≥', '≤', '(', ')', '&&', '||', '==', '≠', '删除', '清空'],
      numberList: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '.'],
      paramsList: ['年纪', '月收入', '抵押品价值', '信用评分', '有担保人']
    }
  },
  watch: {
    keyWord() {
      this.tableRequset.pageIndex = 1
      this.debounceFn()
    }
  },
  mounted() {
    // this.getJudgeFaultLogicAPI()
    this.getAircaftTypeAndModelTreeAPI()
  },
  methods: {
    async getAircaftTypeAndModelTreeAPI(params) {
      const { data } = await getAircaftTypeAndModelTree(params)
      this.menuTreeData = data
      const { data: airConfigData } = await getAirConfiguration()
      this.allAirConfig = airConfigData
      const getAircaftModelAllParams = {
        aircaftTypeCode: '',
        aircaftTypeId: '',
        queryParam: ''
      }
      const { data: data1 } = await getAircaftModelAll(getAircaftModelAllParams)
      this.aircaftModelAll = data1
    },

    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, total }
      } = await getJudgeFaultLogic({ pageSize, pageNum: pageIndex, keyWord, ...params })
      this.tableData = list
      this.tableData.forEach((item, index) => {
        if (index == 0) {
          item.formula = '年纪 ≥ 25 && ( 月收入 ≥ 10000 || 抵押品价值 ≥ 500000 ) / ( 信用评分 ≥ 700 || 有担保人 == 1 )'
        } else {
          item.formula = ''
        }
      })
      // this.tableData = list.map((item) => {
      //   return { ...item, formula: '年纪 ≥ 25 && ( 月收入 ≥ 10000 || 抵押品价值 ≥ 500000 ) / ( 信用评分 ≥ 700 || 有担保人 == 1 )' }
      // })
      this.tableRequset.total = total
      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()
      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) {}
    },

    async treeNodeClick(data) {
      this.currentNode = data
      let dataTree = []
      if (data.type === 1) {
        const { data: data1 } = await getAirConfiguration({ aircraftType: data.id })
        dataTree = data1
        this.getAirConfigParamsAPI({ aircraftType: data.id })
        this.currentNodeKey = data.id
      }
      this.configTreeData = []
      const topNode = { id: '1', name: '整机', children: [] }
      topNode.children = handleTree(dataTree, 'id')
      this.configTreeData.push(topNode)
    },

    treeConfigNodeClick(data) {
      this.$refs.table.clearSelection()
      this.currentConfigNodeKey = this.form.sysId = data.id
      this.currentConfigNode = data
      this.getAirConfigParamsAPI({ sysId: this.currentConfigNodeKey })
    },

    changeModel(item) {
      const matchedItem = this.aircaftModelAll?.find((i) => item === i.aircaftModelId)
      if (matchedItem) {
        return matchedItem.aircaftModelName
      } else {
        return item
      }
    },

    openDialog() {
      this.dialogTitle = '新增'
      this.dialogVisible = true
      this.form.aircraftType = this.currentNode.id
      this.form.sysId = this.currentConfigNodeKey
    },

    handleClose() {
      this.dialogVisible = false
      this.form = {
        id: '',
        model: '',
        hmcCode: '',
        formula: ''
      }
    },

    handleIndexChange(val) {
      this.tableRequset.pageIndex = val
      this.getJudgeFaultLogicAPI()
    },
    handleSizeChange(val) {
      this.tableRequset.pageSize = val
      this.getJudgeFaultLogicAPI()
    },

    handUpdate(row) {
      this.dialogTitle = '编辑'
      this.form = deepClone(row)
      // this.$set(this.form, 'formula', '$$年纪 \\geq 25 \\&\\& (月收入 \\geq 10000 \\parallel 抵押品价值\\geq 500000)\\&\\&(信用评分\\geq 700 \\parallel 有担保人= 1)$$')
      // this.form.formula = ''
      this.dialogVisible = true
    },

    submit() {
      let c = this.form.formula.slice(2, this.form.formula.length - 2).split(' ')
      console.log('c', c)
      let newFormula = c.map((item) => (item === '\\&\\&' ? '&&' : item))
      this.form.formulatr = newFormula.join(' ')
      console.log('this.form', this.form)
      // this.$refs['form'].validate((valid) => {
      //   if (valid) {
      //     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(() => {})
    },

    // 增加参数
    addParams(params) {
      let formula = deepClone(this.form.formula)
      // 先拿到当前的字符 去除前后 $$ 符号 以空格分隔
      let c = formula.slice(2, formula.length - 2).split(' ')
      if (this.paramsList.find((i) => i == c[c.length - 1])) {
        useMessage('error', '不能连续输入两个参数')
        return
      } else if (this.numberList.find((i) => i == c[c.length - 1])) {
        useMessage('error', '参数和数字不能相邻')
        return
      } else {
        c.push(params)
        const str = c.join(' ')
        this.form.formula = `$$${str}$$`
      }
    },

    // 增加数字
    addNumber(number) {
      let formula = deepClone(this.form.formula)
      // 先拿到当前的字符 去除前后 $$ 符号 以空格分隔
      let c = formula.slice(2, formula.length - 2).split(' ')
      if (number == '.' && !this.numberList.find((i) => i == c[c.length - 1])) {
        useMessage('error', '小数点前必须为数字')
        return
      }
      if (this.paramsList.find((i) => i == c[c.length - 1])) {
        useMessage('error', '参数和数字不能相邻')
        return
      } else {
        c.push(number)
        const str = c.join(' ')
        this.form.formula = `$$${str}$$`
      }
    },

    // 增加运算符
    addSymbol(item) {
      let n = deepClone(this.form.formula)
      const syf = ['+', '-', '*', '/', '>', '<', '≥', '≤', '&&', '||', '≠', '==', '\\&\\&']
      if (item == '删除') {
        if (n.length == 0) {
          return
        } else {
          let c = n.slice(2, n.length - 2).split(' ')
          let j = c.slice(0, c.length - 1)
          if (j.length == 0) {
            this.form.formula = ''
            return
          } else {
            const str = j.join(' ')
            this.form.formula = `$$${str}$$`
            return
          }
        }
      }
      if (item == '清空') {
        this.form.formula = ''
      } else {
        // 如果是空
        if (n.length == 0) {
          // 第一位不能输入 syf 里面的任意字符
          if (syf.find((i) => i == item)) {
            useMessage('error', '第一位不能输入运算符')
            return
          }
          this.form.formula = `$$${item}$$`
        } else {
          let c = n.slice(2, n.length - 2).split(' ')
          // 不能连续输入  syf 里面的任意字符
          if (syf.find((i) => i == c[c.length - 1]) && syf.find((i) => i == item)) {
            useMessage('error', '不能连续输入运算符')
            return
          }
          if (item == '&&') {
            c.push('\\&\\&')
            const str = c.join(' ')
            this.form.formula = `$$${str}$$`
          } else {
            c.push(item)
            const str = c.join(' ')
            this.form.formula = `$$${str}$$`
          }
        }
      }
    },

    // 转换公式
    async handleConvertFormula(aircraftType, formula) {
      // '年纪 ≥ 25 && (月收入 ≥ 10000 || 抵押品价值 ≥ 500000) && (信用评分 ≥ 700 || 有担保人 == 1)'
      // '$$年纪 \\geq 25 \\&\\& (月收入 \\geq 10000 \\parallel 抵押品价值\\geq 500000)\\&\\&(信用评分\\geq 700 \\parallel 有担保人= 1)$$'
      let c = formula.split(' ')
      let newFormula = c.map((item, index) => {
        if (item == '&&') {
          return '\\&\\&'
        } else {
          return item
        }
      })
      const str = newFormula.join(' ')
      return `$$${str}$$`
    },

    // 查找相匹配的括号的位置 (公式数组，传入的括号型号，传入括号的位置)
    findBracketPos(formulaArray, bracketType, position) {
      // stack用来存储多层括号,findPos为最终匹配上的括号位置
      let stack = [],
        findPos
      if (bracketType == '(') {
        console.log('findPos1', findPos)
        for (let i = position + 1; i < formulaArray.length; i++) {
          console.log('findPos3', findPos)
          if (formulaArray[i] == '(') {
            stack.push('(')
          } else if (formulaArray[i] == ')') {
            if (stack.length !== 0) {
              stack.pop()
            } else {
              findPos = i
              console.log('findPos2', findPos)
              break
            }
          }
        }
      } else if (bracketType == ')') {
        for (let i = formulaArray.length - 1; i > 0; i--) {
          if (formulaArray[i] == ')') {
            stack.push(')')
          } else if (formulaArray[i] == '(') {
            if (stack.length !== 0) {
              stack.pop()
            } else {
              findPos = i
              break
            }
          }
        }
      }
      return findPos
    }
  }
}
</script>

<style lang="scss">
@import '../index.scss';
.table {
  width: 100%;
  height: calc(100vh - 280px);
  overflow: scroll;
}
::-webkit-scrollbar {
  display: none;
}
</style>
