<template>
  <el-dialog
    v-dialogDrag
    title="流转条件"
    :visible.sync="viewOpen"
    width="1200px"
    append-to-body
    @open="dialogOpen"
    @close="dialogClose"
  >

    <!-- 列表 -->
    <el-table
      ref="table"
      v-loading="loading"
      :data="list"
      max-height="450px"
      border
      :row-key="(row,$index) => $index"
      size="mini"
    >
      <el-table-column label="逻辑运算" align="center" prop="logicalOperation">
        <template slot-scope="scope">
          <!-- <el-input v-model="scope.row.logicalOperation" /> -->
          <el-select v-model="scope.row.logicalOperation" placeholder="请选择逻辑运算符">
            <el-option
              v-for="(option, index) in logicOptions"
              :key="index"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="左括号" align="center" prop="leftParenthesis">
        <template slot-scope="scope">
          <el-select v-model="scope.row.leftParenthesis" placeholder="请选择左括号">
            <el-option
              v-for="(option, index) in leftBracketOptions"
              :key="index"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="数据" align="center" prop="dataSource">
        <template slot-scope="scope">
          <el-select
            ref="selectTree"
            v-model="scope.row.dataSource"
            clearable
            @clear="selectTreeClear(scope.row)"
          >
            <el-option
              :value="scope.row.dataSource"
              style="height: 200px;width: 260px !important;overflow-y: scroll !important;"
            >
              <el-tree
                ref="tree"
                :show-checkbox="false"
                :accordion="true"
                :data="conditionOptions"
                :node-key="scope.row.id"
                :props="defaultProps"
                :highlight-current="true"
                :check-on-click-node="true"
                :check-strictly="true"
                @check="handleDataChange($event, scope.row)"
              />
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="关系运算" align="center" prop="relationalOperation">
        <template slot-scope="scope">
          <!-- <el-input v-model="scope.row.relationalOperation" /> -->
          <el-select v-model="scope.row.relationalOperation" placeholder="请选择关系运算">
            <el-option
              v-for="(option, index) in logicOptions"
              :key="index"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        label="值"
        align="center"
        prop="value"
        width="220"
      >
        <template slot-scope="scope">
          <!-- <el-select v-if="scope.row.htmlType === 'select'" v-model="scope.row.value" /> -->
          <DictSelect v-if="scope.row.dictType || scope.row.htmlType === 'radio'" v-model="scope.row.value" :dict-type="scope.row.dictType.toUpperCase()" />
          <CurrencySelect
            v-else-if="scope.row.htmlType === 'select'"
            v-model="scope.row.value"
            :dict-table="scope.row.dictTable"
            :dict-table-column-code="scope.row.dictTableColumnCode"
            :dict-table-column-name="scope.row.dictTableColumnName"
          />
          <el-date-picker
            v-else-if="scope.row.htmlType === 'datetime'"
            v-model="scope.row.value"
            style="width: 100%;"
            type="datetime"
            placeholder="选择日期时间"
          />
          <el-input v-else-if="scope.row.htmlType=== 'input' || scope.row.htmlType === undefined" v-model="scope.row.value" />
        </template>
      </el-table-column>
      <el-table-column label="右括号" align="center" prop="rightParenthesis">
        <template slot-scope="scope">
          <el-select v-model="scope.row.rightParenthesis" placeholder="请选择右括号">
            <el-option
              v-for="(option, index) in rightBracketOptions"
              :key="index"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        width="120"
      >
        <template slot-scope="{row,$index}">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(row,$index)"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            class="text-danger"
            @click="handleDelete(row,$index)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <p>条件预览:
        <span v-for="(preview,index) in list" :key="index">
          <span> {{ preview.dataSource }}</span>
          <span> {{ preview.relationalOperation }}</span>
          <span> {{ preview.value }}</span>
          <span v-if="index !== list.length - 1"> ||</span>
        </span>
      </p>
      <p>UEL表达式:</p>
      <p>
        <span>${</span>
        {{ UELExpression }}||
        <!-- <span v-if="defaultCondition.conditionExpression && defaultCondition.conditionExpression.body !== 'Y ----'">
          {{ defaultCondition.conditionExpression.body }}
        </span>|| -->
        <span v-for="(oprate,index) in list" :key="index">
          <span v-show="oprate.logicalOperation !== '----'">{{ oprate.logicalOperation }}</span>
          <span v-show="oprate.leftParenthesis !== '----'">{{ oprate.leftParenthesis }}</span>
          <span v-show="oprate.data !== 'N' && oprate.data !== 'Y'">{{ oprate.data }}</span>
          <span v-show="oprate.relationalOperation !== '----'">{{ oprate.relationalOperation }}</span>
          <span v-show="oprate.data !== 'N' && oprate.data !== 'Y'">{{ oprate.value }}</span>
          <span v-show="oprate.rightParenthesis !== '----'">{{ oprate.rightParenthesis }}</span>
          <span v-if="index !== list.length - 1">||</span>
        </span>
        <span>}</span>
      </p>

    </div>

    <span slot="footer" class="dialog-footer">
      <el-button @click="viewOpen = false">取 消</el-button>
      <el-button
        v-hasPermi="['mes:el-master:update']"
        type="primary"
        :loading="ensureLoading"
        @click="handleAddInspectEnsure"
      >确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getDetailTablePage, saveElMaster, getELMaster } from '@/api/bpm/processModel'
// import Treeselect from '@riophae/vue-treeselect' getAllFormPage,
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { isArray } from 'min-dash'
import CurrencySelect from './CurrencySelect.vue'

export default {
  name: 'ConditionExpression',
  components: {
    CurrencySelect
  },
  props: {
    masterModel: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 导出遮罩层
      exportLoading: false,
      ensureLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      isShow: true,
      // 流转条件 列表
      list: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      viewOpen: false,
      conditionOptions: [],
      defaultCondition: {},
      sourceObject: {},
      // 条件预览
      previewCondition: null,
      changeCondition: ['||'],
      pid: null,
      // UEL表达式
      UELExpression: null,
      defaultProps: {
        children: 'children',
        label: 'label',
        disabled: 'selectable'
      },
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        id: null
      },
      // 逻辑运算
      logicOptions: [
        { label: '----', value: '----' },
        { label: '等于', value: '==' },
        { label: '不等于', value: '!=' },
        { label: '大于', value: '>' },
        { label: '小于', value: '<' },
        { label: '大于等于', value: '>=' },
        { label: '小于等于', value: '<=' }
      ],
      // 左括号
      leftBracketOptions: [
        { label: '----', value: '----' },
        { label: '(', value: '(' },
        { label: '[', value: '[' }
      ],
      // 右括号
      rightBracketOptions: [
        { label: '----', value: '----' },
        { label: ')', value: ')' },
        { label: ']', value: ']' }
      ],
      formData: [
        {
          label: '表单数据',
          key: 'formDatas',
          type: 'forms',
          children: []
        },
        {
          label: '流程数据',
          key: 'flowDatas',
          type: 'flow',
          children: []
        }
      ],
      // Y/N
      flowerables: [
        {
          label: '通过',
          argFlag: 'Y',
          type: 'flow'
        },
        {
          label: '不通过',
          argFlag: 'N',
          type: 'flow'
        }
      ],
      selectedNode: null,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    }
  },
  methods: {
    // 列表默认数据
    async getList() {
      const query = {
        nodeId: this.defaultCondition.id,
        resourceId: this.sourceObject.id,
        id: this.masterModel.id || null
      }
      this.loading = true
      getELMaster(query).then(res => {
        this.list = res.data.detailRespList || []
        if (this.list.length === 0 || !isArray(this.list)) {
          this.list = [
            {
              logicalOperation: '',
              leftParenthesis: '',
              dataSource: '',
              relationalOperation: '',
              value: '',
              rightParenthesis: '',
              dataSourceStr: '',
              id: 0,
              newSplicing: ''
            }
          ]
        }
      }).finally(() => {
        this.loading = false
        // this.list = [
        //   {
        //     logicalOperation: '',
        //     leftParenthesis: '',
        //     dataSource: '',
        //     relationalOperation: '',
        //     value: '',
        //     rightParenthesis: '',
        //     dataSourceStr: '',
        //     id: this.list.length,
        //     newSplicing: ''
        //   }
        // ]
      })
      const params = {
        formId: this.$route.query.tableId
      }
      // 获取表单数据
      // const formPage = await getAllFormPage({ pageNo: 1, pageSize: 200 })
      // formPage.data.list = formPage.data.list.map(item => {
      //   item.type = 'forms'
      //   return {
      //     ...item
      //   }
      // })
      // 获取表单下的字段
      const filedPage = await getDetailTablePage(params)
      filedPage.data.columns = filedPage.data.columns.map(item => {
        item.type = 'forms'
        return {
          ...item
        }
      })
      if (filedPage.data.table) {
        filedPage.data.table.type = 'forms'
        const FiledTable = []
        FiledTable.push(filedPage.data.table)
        this.conditionOptions = this.handleToTree(FiledTable, filedPage.data.columns, this.formData, this.flowerables)
      }
    },
    handleToTree(raw1, raw2, dataForm, flows) {
      const rawData = raw1.map(parentNode => ({
        id: parentNode.id,
        selectable: true,
        label: parentNode.classComment, // 父节点的label字段是表单名，显示中文取表说明
        columnName: parentNode.className,
        children: raw2
          .filter(childNode => childNode.tableId === parentNode.id) // 使用filter方法找出所有的子节点并直接添加到父节点的children数组中
          .map(childNode => ({
            label: childNode.columnComment,
            tableId: childNode.tableId,
            dictTable: childNode.dictTable,
            htmlType: childNode.htmlType,
            tableName: childNode.tableName,
            dictType: childNode.dictType,
            dictTableColumnCode: childNode.dictTableColumnCode,
            dictTableColumnName: childNode.dictTableColumnName })) // 使用map方法将子节点数组中的每个元素转换为需要的格式
      }))
      // const rawData =
      dataForm = dataForm.map(dataItem => {
        // 如果type为forms 说明是表单数据
        dataItem.selectable = true
        if (dataItem.type === 'forms') {
          dataItem.children.push(...rawData)
        } else {
          dataItem.children.push(...flows)
        }
        return dataItem
      })
      return dataForm
    },
    /** 取消按钮 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        inspectionNo: undefined,
        inspectionName: undefined,
        inspectionModel: undefined,
        inspectionType: undefined,
        minValue: undefined,
        standValue: undefined,
        maxValue: undefined,
        code: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd(row, $index) {
      this.list.push({ logicalOperation: '',
        leftParenthesis: '',
        dataSource: '',
        relationalOperation: '',
        value: '',
        rightParenthesis: '',
        newSplicing: '||',
        id: this.list.length })
      // 新增滚动条定位到最下面
      this.$nextTick(() => {
        const wrapper = this.$refs.table.$el.querySelector('.el-table__body-wrapper')
        wrapper.scrollTop = wrapper.scrollHeight
      })
    },
    dialogOpen() {
      this.getList()
      if (this.defaultCondition.conditionExpression.body) {
        this.defaultCondition.conditionExpression.body = this.defaultCondition.conditionExpression.body.split('${').join('').split('}').join('')
      }
      this.UELExpression = this.defaultCondition.id + '||' + '(NODE_ID==' + this.defaultCondition.id + ')'
    },
    dialogClose() {
      this.list = []
    },
    /** 删除按钮操作 */
    handleDelete(row, $index) {
      const { id } = row
      const index = this.list.findIndex(item => item.id === id)
      this.list.splice(index, 1)
    },
    handleDataChange(data, row) {
      const isSatisfy = this.list.some(item => item.data === 'Y' || item.data === 'N')
      const { tableId, id, columnName, label, type, argFlag, dictType, htmlType, dictTable, dictTableColumnCode, dictTableColumnName } = data
      if (type === 'flow') {
        if (isSatisfy === false) {
          row.dataSource = label
          row.data = argFlag
          this.selectedNode = row.dataSource
          this.$refs.selectTree.blur()
        } else {
          row.dataSource = null
          row.data = null
          this.$refs.selectTree.blur()
          this.$modal.msgWarning('您已选择过了流程是否通过，请选择表单数据或结束选择!')
        }
      } else {
        if (tableId || id) {
          row.dataSource = label || columnName
          row.data = columnName || label
          row.htmlType = htmlType
          row.id = id
          row.dictTable = dictTable
          row.dictType = dictType
          row.dictTableColumnCode = dictTableColumnCode
          row.dictTableColumnName = dictTableColumnName
          this.selectedNode = row.dataSource
          this.$nextTick(() => {
            this.$refs.selectTree.blur()
            this.$refs.selectTree.visible = false
          })
        }
      }
    },
    // 清空选择
    selectTreeClear(row) {
      row.dataSource = null
      row.data = null
    },
    // 提交
    async handleAddInspectEnsure() {
      const detailReqList = this.list.map(item => {
        const { logicalOperation, leftParenthesis, data, relationalOperation, value, rightParenthesis, dataSource } = item
        return {
          logicalOperation,
          leftParenthesis,
          data,
          relationalOperation,
          value,
          rightParenthesis,
          dataSource
        }
      })
      const params = {
        nodeId: this.defaultCondition.id,
        resourceId: this.sourceObject.id,
        id: this.masterModel.id || null,
        detailReqList
      }
      saveElMaster(params).then(res => {
        this.$modal.msgSuccess('保存成功!')
      })
      this.$emit('conditionList', this.list)
      this.viewOpen = false
    }
  }
}
</script>
<style scoped>
.searchCase {
  width: 100%;
}
.selects {
  position: relative;
}
.icon {
  position: absolute;
  top: 9px;
  right: 30px;
  width: 40px;
  height: 30px;
  border: none;
  padding: 10px;
}
</style>
