<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>
        </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">
        <el-table :data="tableData" ref="table" 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="sysId" width="250" align="center" label="系统">
            <template slot-scope="scope">{{ changeSys(scope.row.sysId) }} </template>
          </el-table-column>
          <el-table-column prop="name" width="250" align="center" label="判据名称"> </el-table-column>
          <el-table-column prop="hmcCode" width="250" align="center" label="HMC码"> </el-table-column>
          <el-table-column prop="remarks" label="公式" align="center">
            <template slot-scope="scope">
              <span><MathJax ref="MathJax" :formula="scope.row.remarks" /></span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="180">
            <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="formRef" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="机型" prop="model">
            <el-select disabled 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="系统" prop="sysId">
            <el-select disabled v-model="form.sysId" placeholder="请选择系统">
              <el-option v-for="item in allAirConfig" :key="item.id" :label="item.name" :value="item.id"> </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="HMC码参数" label-width="100px" prop="attribute1">
            <el-input v-model="form.attribute1" type="textarea" :rows="2" placeholder="请输入HMC码参数，如：发动机排气温度,燃油流量,机匣频率" />
          </el-form-item>
          <el-form-item label="判据名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入判据名称" />
          </el-form-item>
          <el-col :span="24">
            <el-form-item label="公式">
              <MathJax ref="MathJax" :formula="form.remarks" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="参数">
              <div v-if="paramsList.length !== 0">
                <el-button @click="addParams(item)" type="primary" v-for="(item, index) in paramsList" :key="index">{{ item }}</el-button>
              </div>
              <span v-else style="color: white">暂无参数，请去构型参数管理页面添加</span>
            </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-col :span="24">
            <el-form-item label="持续判据">
              <el-button @click="innerVisible = true" type="primary">增加持续判据</el-button>
            </el-form-item>
          </el-col>
        </el-form>
        <el-dialog width="30%" title="增加持续判据" :visible.sync="innerVisible" :before-close="sustainClose" append-to-body>
          <el-form ref="sustainDataFormRef" :model="sustainDataForm" :rules="sustainRules" label-width="80px">
            <el-form-item label="参数">
              <el-select v-model="sustainDataForm.params" placeholder="请选择参数">
                <el-option v-for="item in paramsList" :key="item" :label="item" :value="item"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="符号">
              <el-select v-model="sustainDataForm.symbol" placeholder="请选择符号">
                <el-option v-for="(item, index) in symbolList" :key="index" :label="item" :value="item"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="数值">
              <el-input v-model="sustainDataForm.number" placeholder="请输入数值" />
            </el-form-item>
            <el-form-item label-width="100px" label="持续时间(s)">
              <el-input-number v-model="sustainDataForm.sustainTime" :min="0" :precision="1" :step="0.5" placeholder="请输入持续时间(s)"></el-input-number>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="sustainClose">取 消</el-button>
            <el-button type="primary" @click="submitSustainData">确 定</el-button>
          </span>
        </el-dialog>
        <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 { getAircaftModelAll, getAircaftCatalogAll } from '@/api/als/aircraft'
import { handleTree } from '../utils/common'
import { getAirConfiguration } from '@/api/als/airConfiguration'
import { getAirConfigParams } from '@/api/als/airConfigParams'
import { useMessage } from '@/utils/element-ui'

export default {
  name: 'JudgeFaultLogic',
  components: {},
  data() {
    // 这里存放数据
    return {
      dialogTitle: '新增',
      dialogVisible: false,
      innerVisible: false,
      keyWordData: '',
      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: '',
        sysId: '',
        name: '',
        remarks: '',
        attribute1: ''
      },
      rules: {
        model: [{ required: true, message: '机型不能为空', trigger: 'change' }],
        sysId: [{ required: true, message: '系统不能为空', trigger: 'change' }],
        hmcCode: [{ required: true, message: 'HMC码不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '判据名称不能为空', trigger: 'blur' }]
      },
      sustainRules: {
        params: [{ required: true, message: '参数不能为空', trigger: 'change' }],
        symbol: [{ required: true, message: '符号不能为空', trigger: 'change' }],
        number: [{ required: true, message: '数值不能为空', trigger: 'blur' }],
        sustainTime: [{ required: true, message: '持续时间不能为空', trigger: 'blur' }]
      },
      aircaftModelAll: [],
      allAirConfig: [],
      operatorList: ['+', '-', '*', '/', '>', '<', '≥', '≤', '(', ')', '&&', '||', '==', '≠', '删除', '清空'],
      numberList: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '.'],
      paramsList: [],
      symbolList: ['>', '<', '≥', '≤', '≠', '=='],
      // 持续时间内容
      sustainDataForm: {
        params: '',
        symbol: '',
        number: '',
        sustainTime: ''
      }
    }
  },
  mounted() {
    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({ model: this.currentNodeKey, sysId: this.currentConfigNodeKey })
          this.handleClose()
        }
      } catch (error) {}
    },

    async getJudgeFaultLogicAPI(params) {
      if (this.$refs.table) this.$refs.table.clearSelection()
      const { pageSize, pageIndex } = this.tableRequset
      const {
        data: { list, total }
      } = await getJudgeFaultLogic({ pageSize, pageNum: pageIndex, ...params })
      this.tableData = list
      this.tableData.forEach((item) => {
        const newFormula = item.remarks.replace(/&&/g, '\\&\\&')

        item.remarks = `$$${newFormula}$$`
      })
      this.tableRequset.total = total
    },

    searchClick() {
      this.getJudgeFaultLogicAPI({ model: this.currentNodeKey, sysId: this.currentConfigNodeKey, name: keyWordData })
    },

    async treeNodeClick(data) {
      this.currentNode = data
      let dataTree = []
      if (data.type === 1) {
        dataTree = this.allAirConfig.filter((item) => {
          return item.aircraftType == data.id
        })
        this.getJudgeFaultLogicAPI({ model: 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.getJudgeFaultLogicAPI({ sysId: this.currentConfigNodeKey })
    },

    async openDialog() {
      this.dialogTitle = '新增'
      const {
        data: { list },
        code
      } = await getAirConfigParams({ pageSize: 1000, pageNum: 1, sysId: this.currentConfigNodeKey })
      this.paramsList = []
      if (code == 200) {
        list.forEach((item) => {
          this.paramsList.push(item.name)
        })
        this.dialogVisible = true
      }
      this.form.model = this.currentNode.id
      this.form.sysId = this.currentConfigNodeKey
    },

    handleClose() {
      this.dialogVisible = false
      this.form = {
        id: '',
        model: '',
        hmcCode: '',
        sysId: '',
        name: '',
        remarks: '',
        attribute1: ''
      }
    },
    async handUpdate(row) {
      this.dialogTitle = '编辑'
      this.form = deepClone(row)
      const {
        data: { list },
        code
      } = await getAirConfigParams({ pageSize: 1000, pageNum: 1, sysId: row.sysId })
      this.paramsList = []
      if (code == 200) {
        list.forEach((item) => {
          this.paramsList.push(item.name)
        })
        this.dialogVisible = true
      }
    },

    handleIndexChange(val) {
      this.tableRequset.pageIndex = val
      this.getJudgeFaultLogicAPI({ model: this.currentNodeKey, sysId: this.currentConfigNodeKey })
    },
    handleSizeChange(val) {
      this.tableRequset.pageSize = val
      this.getJudgeFaultLogicAPI({ model: this.currentNodeKey, sysId: this.currentConfigNodeKey })
    },

    submit() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          let c = this.form.remarks.slice(2, this.form.remarks.length - 2).split(' ')
          let newFormula = c.map((item) => (item === '\\&\\&' ? '&&' : item))
          this.form.remarks = newFormula.join(' ')
          switch (this.dialogTitle) {
            case '编辑':
              this.updateJudgeFaultLogicAPI()
              break
            case '新增':
              this.addJudgeFaultLogicAPI()
              break
          }
        }
      })
    },

    async addJudgeFaultLogicAPI() {
      try {
        const { code } = await addJudgeFaultLogic({ ...this.form })
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.getJudgeFaultLogicAPI({ model: this.currentNodeKey, sysId: this.currentConfigNodeKey })
          this.handleClose()
        }
      } catch (error) {}
    },

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

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

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

    changeSys(item) {
      const matchedItem = this.allAirConfig?.find((i) => item === i.id)
      if (matchedItem) {
        return matchedItem.name
      } else {
        return item
      }
    },

    // 增加参数
    addParams(params) {
      let formula = deepClone(this.form.remarks)
      // 先拿到当前的字符 去除前后 $$ 符号 以空格分隔
      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.remarks = `$$${str}$$`
      }
    },

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

    // 增加运算符
    addSymbol(item) {
      let n = deepClone(this.form.remarks)
      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.remarks = ''
            return
          } else {
            const str = j.join(' ')
            this.form.remarks = `$$${str}$$`
            return
          }
        }
      }
      if (item == '清空') {
        this.form.remarks = ''
      } else {
        // 如果是空
        if (n.length == 0) {
          // 第一位不能输入 syf 里面的任意字符
          if (syf.find((i) => i == item)) {
            useMessage('error', '第一位不能输入运算符')
            return
          }
          this.form.remarks = `$$${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.remarks = `$$${str}$$`
          } else {
            c.push(item)
            const str = c.join(' ')
            this.form.remarks = `$$${str}$$`
          }
        }
      }
    },

    // 转换公式
    handleConvertFormula(aircraftType, formula) {
      let c = formula.split(' ')
      let newFormula = c.map((item, index) => {
        if (item == '&&') {
          return '\\&\\&'
        } else {
          return item
        }
      })
      const str = newFormula.join(' ')
      return `$$${str}$$`
    },

    // 增加判据
    submitSustainData() {
      this.$refs['sustainDataFormRef'].validate((valid) => {
        if (valid) {
          const number = Number(this.sustainDataForm.number)
          const sustainTime = Number(this.sustainDataForm.sustainTime)
          const formula = this.form.remarks.slice(2, this.form.remarks.length - 2)
          const newFormula = formula + ` \\&\\&checkVibrationDuration(${this.sustainDataForm.params},'${this.sustainDataForm.symbol}',${number},${sustainTime},时间)`
          this.form.remarks = `$$${newFormula}$$`
          this.sustainClose()
        }
      })
    },

    sustainClose() {
      this.innerVisible = false
      this.sustainDataForm = {
        params: '',
        symbol: '',
        number: '',
        sustainTime: ''
      }
    }
  }
}
</script>

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