<template>
  <el-container class="content-height-fit">
    <inner-sidebar>
      <project-audit-flow-tree @node-click="handleTreeClick" />
    </inner-sidebar>
    <el-container class="resize-fit-container">
      <div class="app-container blue-top-border">
        <div class="filter-container">
          <el-input v-model="listQuery.flowName" placeholder="名称" class="filter-item" clearable @change="getList" />
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
          <el-button
            v-if="$requirePermission('XT.SH.C')"
            v-waves
            class="filter-item"
            type="primary"
            icon="el-icon-edit"
            :disabled="!listQuery.projectId || !listQuery.category"
            @click="handleCreate"
          >新增</el-button>
          <el-button
            v-if="$requirePermission('XT.SH.S')"
            v-show="listQuery.projectId && listQuery.category"
            v-waves
            class="filter-item"
            type="primary"
            icon="el-icon-refresh"
            @click="handleSync"
          >同步</el-button>
          <el-button
            v-if="$requirePermission('XT.SH.S')"
            v-show="listQuery.projectId && listQuery.category"
            v-waves
            class="filter-item"
            type="danger"
            icon="el-icon-delete"
            @click="clear"
          >清空</el-button>
        </div>
        <div class="content-container">
          <el-table v-loading="listLoading" row-key="id" :data="list" border stripe fit highlight-current-row height="calc(100vh - 200px)">
            <div slot="empty">
              <span v-if="listQuery.projectId && listQuery.category">没有数据</span>
              <span v-else>请选择流程类型</span>
            </div>
            <el-table-column label="序号" type="index" align="center" width="80" />
            <el-table-column label="名称" prop="name" align="center" />
            <el-table-column label="条件" prop="conditionDescs" align="center">
              <template slot-scope="{ row }">
                <div v-for="desc in row.conditionDescs" :key="desc.name">
                  <strong style="color:#e83e8c">{{ desc.name }}</strong>
                  <strong style="color:#2e9bff">{{ desc.match }}</strong>
                  <strong>{{ desc.value }}</strong>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="备注" prop="note" align="center" />
            <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
              <template slot-scope="{ row }">
                <el-button type="primary" size="mini" @click="handleSteps(row)">配置步骤</el-button>
                <el-button v-if="$requirePermission('XT.SH.U')" type="primary" size="mini" @click="handleUpdate(row)">修改</el-button>
                <el-button v-if="$requirePermission('XT.SH.D')" size="mini" type="danger" @click="handleDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
          <el-form ref="dataForm" v-loading="editLoading" :rules="rules" :model="flow" label-width="80px">
            <el-form-item label="名称" prop="name">
              <el-input v-model="flow.name" />
            </el-form-item>
            <el-form-item label="备注" prop="note">
              <el-input v-model="flow.note" />
            </el-form-item>
            <el-form-item label="条件" prop="conditionType">
              <el-radio-group v-model="flow.conditionType">
                <el-radio :value="1" :label="1">满足全部条件</el-radio>
                <el-radio :value="2" :label="2">满足任一条件</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="条件列表" prop="conditions">
              <div>
                <el-button type="primary" size="mini" @click="addCondition">新增条件</el-button>
                <el-table border stripe :data="flow.conditions">
                  <el-table-column label="序号" type="index" width="80px" />
                  <el-table-column label="名称">
                    <template slot-scope="{ row }">
                      <el-select v-model="row.fieldId" @change="changeField(row, $event)">
                        <el-option v-for="item in conditionFields" :key="item.id" :label="item.name" :value="item.id" />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="条件">
                    <template slot-scope="{ row }">
                      <match-type-select v-model="row.matchType" />
                    </template>
                  </el-table-column>
                  <el-table-column label="值">
                    <template slot-scope="{ row }">
                      <field-value-select
                        v-if="row.field"
                        v-model="row.value"
                        :project-id="listQuery.projectId"
                        :data-url="row.field.dataUrl"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="操作">
                    <template slot-scope="{ row }">
                      <el-button type="danger" size="mini" @click="deletCondition(row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">确认</el-button>
          </div>
        </el-dialog>
        <el-dialog :close-on-click-modal="false" title="同步" :visible.sync="dialogFormVisible2">
          <el-form ref="dataForm2" v-loading="syncLoading" :rules="rules2" :model="syncData" label-width="80px">
            <el-select v-model="syncData.from" filterable class="w100p">
              <el-option v-for="item in categories" :key="item.code" :value="item.code" :label="item.name" />
            </el-select>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible2 = false">取消</el-button>
            <el-button type="primary" @click="sync()">确认</el-button>
          </div>
        </el-dialog>
      </div>
    </el-container>
    <step-dialog v-model="showSteps" :title="flow.name" :flow-id="flow.id" :project-id="listQuery.projectId" :condition-fields="conditionFields" />
  </el-container>
</template>

<script>
import * as flowApi from '@/api/audit-flow'
import ProjectAuditFlowTree from './components/ProjectAuditFlowTree'
import MatchTypeSelect from './components/MatchTypeSelect'
import FieldValueSelect from './components/FieldValueSelect'
import StepDialog from './components/StepDialog'

import waves from '@/directive/waves' // waves directive
import InnerSidebar from '@/components/InnerSidebar'

import { deepClone } from '@/utils'
import { getAuditFlowTypes } from '@/api/dict-entry'

export default {
  name: 'AuditFlowMng',
  directives: { waves },
  components: {
    ProjectAuditFlowTree,
    InnerSidebar,
    MatchTypeSelect,
    FieldValueSelect,
    StepDialog
  },
  data() {
    var validateConditions = (rule, value, callback) => {
      if (!this.flow.conditions || this.flow.conditions.length === 0) {
        callback()
        return
      }

      var hasInvalidCondition = this.flow.conditions.find(t => !t.fieldId || !t.matchType || !t.value)

      if (hasInvalidCondition) {
        callback(new Error('存在无效的条件'))
      } else {
        callback()
      }
    }

    return {
      categories: [],
      syncData: {
        projectId: undefined,
        from: undefined,
        to: undefined
      },
      syncLoading: false,
      showSteps: false,
      conditionFields: [],
      list: [],
      flow: {
        id: undefined,
        name: undefined,
        category: undefined,
        projectId: undefined,
        conditionType: undefined,
        index: undefined,
        conditions: []
      },
      listLoading: false,
      listQuery: {
        flowName: undefined,
        category: undefined,
        projectId: undefined
      },
      editLoading: false,
      dialogFormVisible: false,
      dialogFormVisible2: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '创建'
      },
      sections: [],
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { max: 64, message: '长度必须少于64个字符', trigger: 'blur' }
        ],
        conditions: [{ validator: validateConditions, trigger: 'blur' }]
      },
      rules2: {
        from: [{ required: true, message: '请选择来源', trigger: 'change' }]
      }
    }
  },
  watch: {
    'listQuery.category': function(val) {
      if (val) {
        flowApi.getConditionField(val).then(res => {
          this.conditionFields = res
        })
      }
    }
  },
  mounted() {
    this.getList()
    getAuditFlowTypes().then(res => {
      this.categories = res
    })
  },
  methods: {
    handleTreeClick(data) {
      if (data.isCategory) {
        this.listQuery.category = data.id
        this.listQuery.projectId = data.projectId
        this.getList()
      } else {
        this.listQuery.projectId = data.id
        this.listQuery.category = undefined
        this.list = []
      }
    },
    getList() {
      this.listLoading = true
      flowApi.getFlows(this.listQuery).then(res => {
        this.list = res
      }).finally(() => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.getList()
    },
    addCondition() {
      var condition = { index: this.flow.conditions.length + 1 }
      if (this.conditionFields.length) {
        condition.fieldId = this.conditionFields[0].id
        condition.field = this.conditionFields[0]
      }
      this.flow.conditions.push(condition)
    },
    deletCondition(row) {
      this.flow.conditions = this.flow.conditions.filter(t => t.index !== row.index)
    },
    changeField(row, fieldId) {
      row.field = this.conditionFields.find(t => t.id === fieldId)
    },
    resetFlow() {
      this.flow = {
        id: undefined,
        name: undefined,
        category: this.listQuery.category,
        conditionType: undefined,
        index: undefined,
        conditions: [],
        projectId: this.listQuery.projectId
      }
    },
    handleCreate() {
      this.resetFlow()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.flow.conditions.forEach((t, index) => {
            t.index = index
          })
          this.editLoading = true
          flowApi.createFlow(this.flow).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          }).finally(() => {
            this.editLoading = false
          })
        }
      })
    },
    handleUpdate(row) {
      this.flow = deepClone(row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.flow.conditions.forEach((t, index) => {
            t.index = index
          })

          this.editLoading = true
          flowApi.updateFlow(this.flow.id, this.flow).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          }).finally(() => {
            this.editLoading = false
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        flowApi.deleteFlow(row.id).then(() => {
          this.getList()
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        }).finally(() => {
          this.listLoading = false
        })
      })
    },
    handleSteps(row) {
      this.flow = row
      this.showSteps = true
    },
    handleSync() {
      this.syncData.projectId = this.listQuery.projectId
      this.syncData.to = this.listQuery.category
      this.dialogFormVisible2 = true
    },
    sync() {
      this.$refs['dataForm2'].validate(valid => {
        if (valid) {
          this.$confirm('执行此操作前请确认已删除所有当前流程，否则可能从来源处同步重复的流程?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.syncLoading = true
            flowApi.sync(this.syncData).then(() => {
              this.getList()
              this.dialogFormVisible2 = false
              this.$notify({
                title: '成功',
                message: '同步成功',
                type: 'success',
                duration: 2000
              })
            }).finally(() => {
              this.syncLoading = false
            })
          })
        }
      })
    },
    clear() {
      this.$confirm('你确认要删除当前分类所有流程?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        flowApi
          .clear({
            projectId: this.listQuery.projectId,
            category: this.listQuery.category
          })
          .then(() => {
            this.getList()
            this.$notify({
              title: '成功',
              message: '清除成功',
              type: 'success',
              duration: 2000
            })
          }).finally(() => {
            this.listLoading = false
          })
      })
    }
  }
}
</script>
