<template>
  <div class="layout-col-detail right-detail-tabs right-list-toolbar">
    <el-toolbar>
      <el-button @click="goBack" type="primary" size="medium" round class="shadow-primary"><i class="fa fa-chevron-left"></i> 返回上页</el-button>
    </el-toolbar>
    <el-tabs class="tabs-wrap" v-model="tabActiveName" @tab-click="onRoleTabsClick">
      <!-- 数据列表面板选择栏 -->
      <el-tab-pane name="dataList">
        <span slot="label">
          <i class="fa fa-building"></i>数据列表</span>
        <!-- 数据列表工具栏 -->
          <el-toolbar>
            <el-col :span="8">
            <el-button @click="addRecordClickHandler" priv="Modules.CustomForm.AddData">
              <i class="fa fa-plus"></i>添加</el-button>
            </el-col>
            <el-col :span="10" class="search-box-r tool-search-box-r">
              <el-input v-model="searchFormListValue" @keyup.enter.native="searchFormList" placeholder="" class="search-bar-algin-toolbar"></el-input>
              <span class="search-icon"><i class="fa fa-search" @click="searchFormList" title="查询"></i></span>
            </el-col>
          </el-toolbar>
          <div class="padding-top-bottom-intab scroll">
          <!-- 数据列表表格 -->
          <el-table :data="customFormListData" tooltip-effect="dark" v-loading="customFormListDataLoading" @selection-change="onCustomFormListSelectionChange">
            <el-table-column type="index" width="55" label="序号"></el-table-column>
            <!-- <el-table-column type="selection" align="center"></el-table-column> -->
            <!-- 根据后台获取到的数据自定义表格的行 -->
            <el-table-column v-for="(field,index) in columns" :key="field.code" :prop="field.code" :label="field.name">
              <template slot-scope="scope">
                <el-button v-if="index === 0" type="text" priv="Modules.CustomForm.EditData" class="table-title-button" :title="scope.row.content[field.code]" @click.stop="editRecordClickHandler(scope.row)">{{scope.row.content[field.code]}}
                </el-button>
                <span v-else>{{scope.row.content[field.code]}}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="right">
              <template slot-scope="scope">
                <el-button @click.stop="editRecordClickHandler(scope.row)" type="text" title="编辑" priv="Modules.CustomForm.EditData">
                  <i class="fa fa-edit f16"></i></el-button>
                <el-button @click.stop="deleteRecordClickHandler([scope.row])" type="text" title="删除" priv="Modules.CustomForm.DeleteData">
                  <i class="fa fa-times f16"></i></el-button>
              </template>
            </el-table-column>
          </el-table>
          <!--分页-->
          <div class="page-wrap">
            <el-pagination @size-change="customFormListDataSizeChangeHandler" @current-change="customFormListDataCurrentChangeHandler"
              :current-page.sync="listCurrentPage" :page-sizes="listPageSizes" :page-size="listPageSize" :total="listTotal"
              layout="total, sizes, ->, prev, pager, next, jumper">
            </el-pagination>
          </div>
        </div>
      </el-tab-pane>
      <!-- 配置信息面板选择栏 -->
      <el-tab-pane name="settingInfo">
        <span slot="label">
          <i class="fa fa-cog"></i>配置信息</span>
        <div class="settingPanel" v-loading="customFormSettingInfoPanelLoading">
          <el-toolbar>
            <el-button @click="saveSettingInfoClickHandler" priv="Modules.CustomForm.ConfigSave">
              <i class="fa fa-save"></i>保存</el-button>
          </el-toolbar>
          <div class="padding-top-bottom-intab scroll">
            <!-- 自定义表单配置信息表单 -->
            <el-form :model="tmpSettingInfoData" ref="settingInfoDataForm" label-width="200px" class="customform-config-form">

              <div class="panel-fieldset">
                <h4 class="panel-legend">基本设置</h4>
                <el-form-item label="表单提交的目标邮箱：" prop="email">
                  <el-input class="form-item" v-model="tmpSettingInfoData.email"></el-input>
                </el-form-item>
                <el-form-item label="表单简易工作流：" prop="workflowID">
                  <el-select class="form-item" v-model="tmpSettingInfoData.workflowID">
                    <el-option v-for="item in simpleWorkflows" :key="item.ID" :label="item.name" :value="item.ID"></el-option>
                  </el-select>
                </el-form-item>
              </div>
              <customFormConfigExtendAction :extends.sync="tmpSettingInfoData"></customFormConfigExtendAction>
            </el-form>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <customFormData-dialog :ID="modelID" :PKValue="PKValue" :formData="customFormData" :show.sync="createRecordDataModal" @callback="loadingDataList"></customFormData-dialog>
  </div>
</template>

<script>
import util from '@src/common/util.js'
import customFormConfigExtendAction from '../membercustomform/customFormConfigExtendAction.vue'
import customFormDataDialog from './customFormDataDialog.vue'

export default {
  props: {
    ID: [String, Number],
    tab: String
  },
  data() {
    return {
      modelID: '',
      PKValue: '',
      customFormData: {},
      simpleWorkflows: [],
      customFormSettingInfoPanelLoading: false, // 配置信息页数据加载动画
      tmpSettingInfoData: {
        memberMenu: 'N'
      }, // 自定义表单配置信息
      tabActiveName: 'dataList', // 初始页面时默认选中面板
      searchFormListValue: '', // 搜索数据列表框的值
      selectedRows: [], // 选中的自定义表单列表数据行
      isEdit: false, // 判断弹框是由添加还是编辑显示出来
      formPropCacheData: [], // 表单对应属性缓存数据
      createRecordDataTitle: '', // 添加记录弹框标题
      createRecordDataModal: false, // 添加记录弹框控制
      tmpCreateRecordData: {}, // 添加记录弹框数据
      customFormListData: [], // 数据列表数据
      customFormListDataLoading: false, // 数据列表数据加载动画
      searchFormName: '', // 自定义表单的查询值
      listCurrentPage: 1, // 数据列表分页当前页
      listPageSizes: [10, 20, 30], // 数据列表分页当前页大小选择
      listPageSize: 10, // 数据列表分页当前页大小
      listTotal: 0, // 数据列表分页数据总条数
      columns: []
    }
  },
  mounted() {
    this.modelID = this.ID
    let tabs = ['dataList', 'settingInfo']
    this.tabActiveName = tabs.includes(this.tab) ? this.tab : 'dataList'
    this.$router.replace(`/plugins/customForm/${this.ID}/${this.tabActiveName}`)
    this.loadingDataList()
  },
  methods: {
    goBack() {
      this.$router.push('/plugins/customForm')
    },
    // 自定义表单数据列表改变分页大小触发事件
    customFormListDataSizeChangeHandler(val) {
      this.listPageSize = val
      this.loadingDataList()
    },
    // 自定义表单数据列表改变当前页触发事件
    customFormListDataCurrentChangeHandler(val) {
      this.listCurrentPage = val
      this.loadingDataList()
    },
    // 加载数据列表数据方法
    async loadingDataList() {
      this.customFormListDataLoading = true
      let res = await axios.get(`/ui/customforms/${this.ID}/datas`, {
        params: {
          searchValue: encodeURIComponent(this.searchFormListValue),
          pageIndex: this.listCurrentPage,
          pageSize: this.listPageSize
        }
      })
      this.listTotal = res.data.total
      this.customFormListData = res.data.data
      res = await axios.get(`/ui/customforms/${this.ID}`)
      let modelSchema = res.data.data.modelSchema
      this.columns = []
      modelSchema.forEach(g => {
        g.columns.forEach(c => { this.columns.push(c) })
      })

      this.customFormListDataLoading = false
    },

    // 搜索数据列表数据
    searchFormList() {
      this.loadingDataList()
    },

    // 加载配置信息方法
    async loadingSettingInfo() {
      this.customFormSettingInfoPanelLoading = true
      try {
        let data = await axios.get(`/ui/customformconfig/${this.modelID}`, {})
        this.tmpSettingInfoData = data.data.data
        if (!this.tmpSettingInfoData.memberMenu) {
          Vue.set(this.tmpSettingInfoData, 'memberMenu', 'N')
        }
        let res = await axios.get('/ui/simpleworkflow')
        this.simpleWorkflows = res.data.data
      } catch (e) {
      }
      this.customFormSettingInfoPanelLoading = false
    },
    // 点击面板按钮改变面板页触发事件
    onRoleTabsClick() {
      // 判断是否选中配置信息
      if (this.tabActiveName === 'settingInfo') {
        this.loadingSettingInfo()
      }
      // 判断是否选中数据列表
      if (this.tabActiveName === 'dataList') {
        this.loadingDataList()
      }
      this.$router.replace(`/plugins/customForm/${this.ID}/${this.tabActiveName}`)
    },
    // 数据列表改变当前选中行触发事件
    onCustomFormListSelectionChange(selection) {
      let a = selection.slice()
      this.selectedRows = a.concat()
    },
    // 添加数据列表数据
    async addRecordClickHandler() {
      this.PKValue = ''
      this.createRecordDataModal = true
    },
    // 编辑数据列表数据
    async editRecordClickHandler(row) {
      // 判断当前是否有选中的数据列表的行
      if (this.selectedRows.length === 0 && !row.modelID) {
        this.$alert('请先选择要编辑的行', '提示', {
          type: 'info'
        })
        return
      }
      this.PKValue = row.PKValue
      this.customFormData = Object.assign({}, row)
      this.createRecordDataModal = true
    },
    // 删除数据列表数据
    async deleteRecordClickHandler(rows) {
      // 判断当前是否有选中的数据列表的行
      if (rows.length === 0) {
        this.$alert('请先选择要删除的记录', '提示', {
          type: 'info'
        })
        return
      }
      try {
        await this.$confirm('确定删除吗，删除后无法恢复。是否继续删除？', '删除确认', {
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (e) {
        return
      }
      let rowIds = []
      rows.forEach(function(row) {
        rowIds.push(row.PKValue)
      })
      if (!rowIds) {
        return
      }
      let strIds = rowIds.join(',')
      let res = await axios.delete(`/ui/customforms/${strIds}`, {
        params: {
          modelID: this.modelID
        }
      })
      util.showResponseMessage(res.data)
      if (res.data.status === 1) {
        this.loadingDataList()
      }
    },
    // 保存配置信息按钮点击触发事件
    async saveSettingInfoClickHandler() {
      if (!this.modelID) {
        this.$alert('请先选择一条自定义表单数据', '提示', {
          type: 'info'
        })
        return
      }
      try {
        await util.validateForm(this.$refs['settingInfoDataForm'])
      } catch (e) {
        util.showErrorMessageBox(e)
        return
      }
      this.customFormSettingInfoPanelLoading = true
      try {
        let res = await axios.put(`/ui/customformconfig/${this.modelID}`, this.tmpSettingInfoData)
        this.customFormSettingInfoPanelLoading = false
        util.showResponseMessage(res.data)
      } catch (e) {
        this.customFormSettingInfoPanelLoading = false
      }
    }
  },
  components: {
    customFormConfigExtendAction,
    'customFormData-dialog': customFormDataDialog
  }
}
</script>
<style>
.customform-config-form .form-item {
  width: 100%;
  max-width: 300px;
}
</style>
<style scoped>
.ul li {
  list-style: none;
}

.page-wrap {
  width: 100%;
  position: relative;
}
.padding-top-bottom .search-bar {
  padding-bottom: 5px;
}

.settingPanel .toolbar {
  border-bottom: 1px solid #ccc;
  padding: 5px;
}

.settingPanel .form-header {
  font-size: 18px;
  font-weight: bold;
  margin-left: 15px;
  margin-top: 10px;
}

.settingPanel .e-input,
.selectFrame {
  width: 240px;
}

.settingPanel .e-through {
  margin-left: 5px;
  width: 60px;
}

.search-input {
  width: 230px;
}

</style>
