<template>
  <div class="verification-management page-wrap">
    <dee-search-server
      ref="newForm"
      v-model="form"
      class="mpb0"
      :form-data="formData"
      @search="query(true,true)"
    />

    <dee-table
      :index-row="{title:'序号',width: '80'}"
      :data="tableData"
      :columns="columns"
      :options="userOptions"
      :pagination="pagination"
      selection-row
      @selection-change="checkrows"
      @pagination-size-change="changePageSize"
      @pagination-current-change="changePageNum"
    >
      <dee-tools slot="header" :tools="userTools" mode="normal" />
    </dee-table>

    <dee-dialog
      :visible.sync="dialogVisible"
      width="1020px"
      :title="title"
      :before-close="handleClose"
      :destroy-on-close="true"
    >
      <el-scrollbar style="height:450px">
        <paramsForm ref="paramsForm" :is-edit="isEdit" :apps="apps" :cur-row="curRow" />
      </el-scrollbar>
      <span style="display:flex;justify-content: center;">
        <el-button
          slot="sub_text"
          type="primary"
          class="searchBtn"
          @click="saveItems"
        >确定</el-button>

        <el-button
          slot="sub_cancel"
          class="searchBtn"
          @click="handleClose"
        >取消</el-button>
      </span>

    </dee-dialog>
  </div>

</template>
<script>
import paramsForm from './form.vue'
import { getItems, saveItems, updateItems, removeItems } from '@/api/mgt/verification.js'
export default {
  name: 'VerificationManagement',
  components: { paramsForm },

  props: {},
  data() {
    return {
      isEdit: false,
      title: '新增计算方法',
      dialogVisible: false,
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
        pageSizes: [10, 20, 50]
      },
      selectedRows: [],
      form: {
        appId: '',
        name: ''
      },
      curRow: {},
      columns: [{ title: '操作', minWidth: 80, align: 'center', component: {
        render: (h, row, column, $index) => {
          let operationHtml = ''
          if (!row.systemFlag) {
            operationHtml = <img src ={ require('@/icons/components/new/c-edit.png') }
              title = '编辑'
              style = 'width:16px;height:16px;cursor:pointer;'
              v-on:click= {() => {
                this.dialogVisible = true
                this.title = '编辑计算方法'
                this.curRow = row
                this.isEdit = true
              }}
            />
          }
          return operationHtml
        }
      }},
      { title: '方法类型', key: 'typeState', align: 'center', minWidth: 120 },
      { title: '所属应用', key: 'appName', align: 'center', minWidth: 120 },
      { title: '显示名称', key: 'displayName', align: 'center', minWidth: 120 },
      { title: '方法名称', key: 'name', align: 'center', minWidth: 120 },
      { title: '方法参数', key: 'paramsName', align: 'center', minWidth: 120 }
      ],
      userOptions: {
        fit: true,
        defaultExpandAll: true,
        highlightCurrentRow: true
      },
      userTools: [
        {
          type: 'icon',
          name: '新增',
          // icon: require('@/icons/designcenter/add.png'),
          icon: require('@/icons/designcenter/c-add.png'),
          handler: {
            click: () => {
              this.dialogVisible = true
              this.title = '新建计算方法'
              this.isEdit = false
              this.curRow = {}
            }
          }
        },
        {
          type: 'icon',
          name: '删除',
          // icon: require('@/icons/designcenter/del.png'),
          icon: require('@/icons/designcenter/c-creatbackups.png'),
          handler: {
            click: () => {
              this.removeRows()
            }
          }
        }
      ],
      tableData: [],
      apps: []
    }
  },
  computed: {
    formData() {
      return [
        {
          key: 'name',
          title: '名称',
          component: {
            name: 'el-input',
            clearable: true
          }
        },
        {
          key: 'appId',
          title: '所属应用',
          component: {
            name: 'el-select',
            options: this.apps
          }
        }
      ]
    }
  },
  watch: {
    'form.appId'(id) {
      if (id) {
        this.form.appName = this.apps.find(app => app.value === id).label
      }
    }
  },
  created() {
    this.getApps()
  },
  methods: {
    query(flag = false, userAction) {
      if (flag) {
        this.pagination.currentPage = 1
      }
      getItems({
        ...this.form,
        page: this.pagination.currentPage,
        size: this.pagination.pageSize
      }, userAction).then(r => {
        const typeState = ['全局方法', '单一应用方法']
        if (r.items) {
          this.pagination.total = r.items.totalElements
          console.log('APPS', this.apps)
          this.tableData = r.items.content.map(row => {
            const app = (this.apps || []).find(m => m.value === row.appId)
            if (app) {
              row.appName = app.label
            }
            row.typeState = typeState[row.type]
            row.show = true
            row.paramsName = row.params && row.params.map(el => {
              if (el.type === 0) {
                return '属性'
              } else if (el.type === 1) {
                return '操作符'
              } else if (el.type === 2) {
                return '输入值'
              } else if (el.type === 3) {
                return '枚举'
              }
            }).join(',')
            return row
          })
        }
      })
    },

    changePageSize(pageSize) {
      this.pagination.pageSize = pageSize
      this.pagination.currentPage = 1
      this.query(false, true)
    },
    changePageNum(pageNum) {
      this.pagination.currentPage = pageNum
      this.query(false, true)
    },
    getApps() {
      const params = {
        'indices': ['DxApplication'],
        'pageFrom': 1,
        'pageSize': 9999,
        'openProps': [],
        'searchItems': {
          'operator': 'AND',
          'items': [{
            'fieldName': 'isDisable',
            'operator': 'EQ',
            'value': false
          }]
        }
      }

      this.$api.searchApi('DxApplication', params).then(res => {
        this.apps = res.items.content.map(m => {
          return {
            label: m.name,
            value: m.id
          }
        })
        this.form.appId = this.apps[0] && this.apps[0].value
      })
    },
    handleClose() {
      this.dialogVisible = false
      this.curRow = {}
    },
    saveItems() {
      this.$refs['paramsForm'].$refs['form'].validate().then(status => {
        if (status) {
          const params = JSON.parse(JSON.stringify(this.$refs['paramsForm'].getData()))
          for (let i = 0; i < params.params.length; i++) {
            const { type, list } = params.params[i]
            if (Number.isInteger(type)) {
              if (type === 3 && list.length === 0) {
                this.$message.warning('枚举属性不能为空')
                return
              }
            } else {
              this.$message.warning('参数类型不能为空')
              return
            }
          }
          // if (params.params && !params.params.length) return this.$message.warning('参数不能为空')
          const updateFun = params.id ? updateItems : saveItems
          const msg = params.id ? '修改成功' : '新增成功'
          updateFun(params).then(r => {
            this.$message.success(r.items || msg)
            this.query()
            this.dialogVisible = false
            this.curRow = {}
          })
        }
      })
    },
    removeRows() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请先选择计算方法')
        return
      }
      let flag = false
      this.selectedRows.forEach(m => {
        if (m.systemFlag) {
          flag = true
        }
      })
      if (flag) {
        this.$utils.showMessageError('内置方法不能删除')
        return
      }
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = this.selectedRows.map(r => 'ids=' + r.id).join('&')
        removeItems(ids).then(res => {
          this.query()
          this.selectedRows = []
          this.$message.success('删除成功')
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    checkrows(rows) {
      this.selectedRows = rows
    },
    reset() {
      this.$refs.newForm.$refs.form.resetFields()
      this.query(false, true)
    }
  }

}
</script>
<style lang="scss">
  @import "../../styles/index";
  @import "../../styles/variables";
  @import "../../styles/mixin";

  .verification-management {
    .dee-table{
      height: calc( 100% - 50px);
      .dee-table-body{
        height: calc( 100% - 92px);
        overflow-y: scroll;
      }
    }
    .permission-contant-tree {
      padding: 8px;
      overflow-y: auto;
      height: 100%
    }

    /deep/ .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
      @include colorWithOpacity(background-color, .2)
    }

    /deep/ .el-tabs__header {
      margin-bottom: 0;
    }
  }
</style>