<!--管理通用问题-->
<template>
  <div class="commonQustMgrPop">
    <dialog-edit :visible.sync="dialogVisible"
                 :closeLabel="$t('common.cancel')"
                 :editModel="editModel" :form="form"
                 :saveFlag="false"
                 :title="$t('commonQustMgrPopList.title')">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="commonQus-class" required>
         <el-form-item :label="$t('effectDealFeedBackMain.commonQuestionContent')" prop="commonQuestionContent" label-width="100px" >
          <el-input ref="commonQus" v-model="ruleForm.commonQuestionContent" :value="value" :placeholder="$t('commonQustMgrPopList.commonQusPlaceholder')" maxlength="500"></el-input>
        </el-form-item>
        <el-form-item :label="$t('effectDealFeedBackMain.traceUserName')" prop="traceUserId" label-width="100px">
          <trace-user-select-list v-model="ruleForm.traceUserId" :queryParas="form" ref="userSelect" width="100%"></trace-user-select-list>
        </el-form-item>
      </el-form>
      <el-row :gutter="100">
        <el-col :span="12">
          <div class="grid-content bg-purple">
          <externalTransition :isCollapse="false" :title="$t('commonQustMgrPopList.allQus')" :isActive="false">
          </externalTransition>
          <el-row type="flex" justify="space-between">
            <el-col :span="12">
                <el-form-item :label="$t('effectDealFeedBackMain.replyLawContent')" prop="feedbackQuestionContent" label-width="80px" class="lsyj" >
                  <el-input ref="commonQus" v-model="searchForm1.feedbackQuestionContent" :value="value" style="width:240px"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="12" align="right">
                  <auth-button type="primary" @click="searchUnrelated" class="iconfont iconycchaxun" :label="$t('common.search')" size="medium"></auth-button>
                  <auth-button type="primary" @click="chooseData" class="iconfont icongou" :label="$t('projectCompany.btnDone')" size="medium"></auth-button>
            </el-col>
          </el-row>
          <data-table :api="editModel === 'E' ? null : qustListApi"
                      ref="datable1"
                      :loadPage="editModel === 'E' ?'getDefaultInfo':'getList'"
                      :loadCount.sync="loadCount"
                      :columns="columns"
                      :showPage="true"
                      :queryParas="queryParas"
                      :showSelection="showSelection"
                      :sourceData.sync="sourceData1"
                      @handleFilter="editModel === 'E' ?loadEditData(queryParas):handleFilter"
                      @selectRowChange="selectRowChange1"
                      @sizeChange="loadEditData(queryParas)"
                      @currentChange="loadEditData(queryParas)"
                      class="pagination-setting"
                      height="390"
                      stripe>
              <template slot="feedbackQuestionContent" slot-scope="scope">
                <span-plus :index="scope.data.$index" :text="scope.data.row.feedbackQuestionContent"></span-plus>
              </template>
            </data-table>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="grid-content bg-purple-light">
            <externalTransition :isCollapse="false" :title="$t('commonQustMgrPopList.relevanceQus')" :isActive="false">
            </externalTransition>
            <el-row type="flex" justify="space-between">
              <el-col :span="12">
                  <el-form-item :label="$t('effectDealFeedBackMain.replyLawContent')" prop="feedbackQuestionContent" label-width="80px" class="lsyj" >
                    <el-input ref="commonQus" v-model="searchForm2.feedbackQuestionContent" :value="value" style="width:240px"></el-input>
                  </el-form-item>
              </el-col>
              <el-col :span="12" align="right">
                    <auth-button type="primary" @click="searchRelated" class="iconfont iconycchaxun" :label="$t('common.search')" size="medium"></auth-button>
                    <auth-button type="default" @click="cancelChoose" class="iconfont iconquxiao" :label="$t('feedBackMain.cancelChoose')" size="medium"></auth-button>
              </el-col>
            </el-row>
            <data-table :sourceData="sourceData3"
                        :columns="columns1"
                        :showPage="false"
                        :showSelection="showSelection"
                        :selectTable="selectTable"
                        @selectRowChange="selectRowChange2"
                        class="pagination-setting"
                        height="390"
                        stripe>
              <template slot="feedbackQuestionContent" slot-scope="scope">
                <span-plus :index="scope.data.$index" :text="scope.data.row.feedbackQuestionContent"></span-plus>
              </template>
                <template slot="paginationLeft">
                  <div style="float: right">
                    <el-pagination  @size-change="handleSizeChange"
                                    @current-change="handleCurrentChange"
                                    :current-page.sync="queryParas1.pageIndex"
                                    :page-sizes="pageSizes"
                                    :page-size="queryParas1.pageSize"
                                    :layout="pageLayout"
                                    prev-text="上一页"
                                    next-text="下一页"
                                    :page-count="pageCount"
                                    ref="dataTable"
                                    :total="currentTotal">
                      <span style="text-align: center">{{queryParas1.pageIndex}}</span>
                    </el-pagination>
                  </div>
                </template>
              </data-table>
          </div>
        </el-col>
        </el-row>
      <template slot="footer">
        <auth-button :disabled="disabled" v-if="classType='true'"  :label="saveLabel"  size="medium"  type="primary" @click="save"></auth-button>
        <auth-button :disabled="disabled" v-if="classType='true'&&editModel==='C'"  :label="saveNewLabel"  size="medium"  type="primary" @click="saveAndCreate"></auth-button>
      </template>
    </dialog-edit>
  </div>
</template>

<script>
import BasePage from '@/pages/baseEditPage'
import { DialogEdit, dymForm, DataTable, authButton, SpanPlus } from 'newepoch-components'
import externalTransition from '@/components/element/assetoutfeedback/externalTransition'
import coordManageApi from '@/api/assetoutfeedback/coordManage/coordManageApi'
import traceUserSelectList from '@/components/element/assetoutfeedback/traceUserSelectList'
import * as format from '@/filters/index'
export default {
  extends: new BasePage(),
  components: { DialogEdit, dymForm, DataTable, authButton, externalTransition, traceUserSelectList, SpanPlus },
  name: 'commonQustMgrPop',
  props: {
    form: {
      type: Object,
      default () {
        return {}
      }
    },
    editModel: {
      type: String,
      default () {
        return ''
      }
    },
    commonInfo: {
      type: Object,
      default () {
        return {}
      }
    },
    confirmLabel: {
      type: String,
      default () {
        return this.$i18n.messages[this.$i18n.locale].projectCompany.btnDone
      }
    },
    cancelLabel: {
      type: String,
      default () {
        return this.$i18n.messages[this.$i18n.locale].commonQustMgrPopList.cancelSelect
      }
    },
    saveLabel: {
      type: String,
      default () {
        return this.$i18n.messages[this.$i18n.locale].commonQustMgrPopList.save
      }
    },
    saveNewLabel: {
      type: String,
      default () {
        return this.$i18n.messages[this.$i18n.locale].commonQustMgrPopList.saveAndCreate
      }
    }
  },
  data () {
    return {
      title: '',
      value: '',
      loadCount: 0,
      mainQuestion: {}, // 已关联主问题
      pageCount: 0,
      pageSizes: [10, 20, 30, 40, 50],
      pageLayout: 'total, sizes, prev, pager, next, jumper',
      currentTotal: 0,
      queryParas: {
        pageIndex: 1,
        pageSize: 10
      },
      queryParas1: {
        pageIndex: 1,
        pageSize: 10
      },
      disabled: false,
      showSelection: true,
      ruleForm: {},
      searchForm1: { extOrgOpinionContent: '' },
      searchForm2: { extOrgOpinionContent: '' },
      rules: {
        commonQuestionContent: [
          { required: true, message: this.$t('commonQustMgrPopList.commonQusPlaceholder'), trigger: 'blur' }]
      },
      columns: [
        {
          prop: 'assetCode',
          align: 'center',
          width: '24px',
          label: this.$i18n.messages[this.$i18n.locale].common.payCode
        }, {
          prop: 'feedbackQuestionContent',
          align: 'left',
          width: '24px',
          slot: true,
          label: this.$i18n.messages[this.$i18n.locale].effectDealFeedBackMain.replyLawContent
        }, {
          prop: 'traceUserName',
          align: 'center',
          width: '24px',
          label: this.$i18n.messages[this.$i18n.locale].effectDealFeedBackMain.traceUser
        }
      ],
      columns1: [
        {
          prop: 'assetCode',
          align: 'center',
          width: '24px',
          label: this.$i18n.messages[this.$i18n.locale].common.payCode
        }, {
          prop: 'feedbackQuestionContent',
          align: 'left',
          width: '24px',
          label: this.$i18n.messages[this.$i18n.locale].effectDealFeedBackMain.replyLawContent
        }, {
          prop: 'traceUserName',
          align: 'center',
          width: '24px',
          label: this.$i18n.messages[this.$i18n.locale].effectDealFeedBackMain.traceUser
        }
      ],
      sourceData: [], // 所有已关联
      allRelated: [],
      sourceData1: [],
      sourceData2: [],
      checkedData: [],
      cancelData: []
    }
  },
  methods: {
    // 每页条数变更时
    handleSizeChange (val) {
      this.queryParas.pageSize = val
      this.queryParas.pageIndex = 1
    },
    // 当前页数改变时
    handleCurrentChange (val) {
      this.queryParas.pageIndex = val
    },
    handleCancle () {
      this.dialogVisible = false
    },
    selectRowChange1 (data) {
      this.checkedData = data
    },
    selectRowChange2 (data) {
      this.cancelData = data
    },
    // 选择确定
    chooseData () {
      let data = this.checkedData
      this.sourceData = this.filterArraySelf(this.sourceData, data)
      this.sourceData2 = this.filterArraySelf(this.sourceData2, data)
      this.currentTotal = this.sourceData2.length
    },
    // 取消选择
    cancelChoose () {
      let data = this.cancelData
      let flag = 0
      if (this.mainQuestion.toString() !== '{}' && this.mainQuestion.relationCommonDealFlag === '2' && this.mainQuestion.questionStatus > '6') {
        let arr = []
        arr = this.allRelated.filter(item => {
          if (data.indexOf(item) > -1) {
            data.splice(data.indexOf(item), 1)
            return item
          }
        })
        if (arr.length > 0) {
          flag = 1
        }
      }
      if (flag === 0) {
        this.sourceData = this.filterArray(this.sourceData, data)
        this.sourceData2 = this.filterArray(this.sourceData2, data)
        this.currentTotal = this.sourceData2.length
      } else {
        this.warning(format.formatDict(this.mainQuestion.questionStatus, 'AUDIT_OUT_QUST_FEEDBACK_STATUS') + ',已关联问题不可移除')
      }
    },
    // 选择框禁用方法
    selectTable (row) {
      if (this.mainQuestion.toString() !== '{}' && row.relationCommonDealFlag === '2' && row.questionStatus >= '6') {
        return false
      } else {
        return true
      }
    },
    // 数组对象去重
    filterArraySelf (a, b) {
      let obj = {}
      a = a.concat(b).reduce((item, next) => {
        if (!obj[next.keyId]) {
          obj[next.keyId] = true
          item.push(next)
        }
        return item
      }, [])
      return a
    },
    // 删除
    filterArray (a, b) {
      let c = a.filter(items => {
        if (!b.includes(items)) {
          return items
        }
      })
      return c
    },
    loadEditData (data, type) {
      if (this.editModel === 'E') {
        this.ruleForm = {
          commonQuestionContent: this.commonInfo.commonQuestionContent,
          traceUserId: this.commonInfo.traceUserId
        }
        this.createQustApi.getDefaultInfo(data).then(res => {
          if (res.success) {
            if (res.data.waitQuesInfos && res.data.waitQuesInfos.datas) {
              this.$refs.datable1.buildTableData(res.data.waitQuesInfos.datas, res.data.waitQuesInfos.totalRow)
              // console.log(res.data.waitQuesInfos.totalRow)
              // this.sourceData1 = res.data.waitQuesInfos.datas
            }
            if (res.data.alreadyQuesInfos && type !== 'search') {
              let ques = []
              this.sourceData = res.data.alreadyQuesInfos
              this.allRelated = res.data.alreadyQuesInfos
              this.sourceData2 = res.data.alreadyQuesInfos
              this.currentTotal = this.sourceData2.length
              ques = this.sourceData2.filter(item => {
                if (item.relationCommonDealFlag === '2') {
                  return item
                }
              })
              this.mainQuestion = ques[0]
            }
          }
        })
      }
    },
    // 待关联查询
    searchUnrelated () {
      if (this.editModel === 'C') {
        Object.assign(this.queryParas, this.searchForm1)
        this.handleFilter()
      } else {
        Object.assign(this.queryParas, this.searchForm1)
        this.loadEditData(this.queryParas, 'search')
      }
    },
    // 已关联查询
    searchRelated () {
      var reg = new RegExp(this.searchForm2.feedbackQuestionContent)
      this.sourceData2 = this.sourceData.filter((value) => { // 过滤数组元素
        // return value.feedbackQuestionContent.includes(this.searchForm2.feedbackQuestionContent)
        if (value.feedbackQuestionContent.match(reg)) { // 如果包含字符返回true
          return true
        }
      })
      this.currentTotal = this.sourceData2.length
    },
    saveData (type) {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          if (this.sourceData.length === 0) {
            this.warning('请选择关联问题')
            return
          }
          let flag = this.sourceData.filter(item => {
            if (item.traceUserId && item.traceUserId === this.ruleForm.traceUserId) {
              return true
            }
          })
          if (flag.length === 0) {
            this.warning('至少一条关联问题合规人员是跟进人')
            return
          }
          if (this.mainQuestion.relationCommonDealFlag === '2' && this.mainQuestion.questionStatus >= '6' && this.ruleForm.traceUserId !== this.commonInfo.traceUserId) {
            this.warning(format.formatDict(this.mainQuestion.questionStatus, 'AUDIT_OUT_QUST_FEEDBACK_STATUS') + ',不可改变跟进人')
            return
          }
          let submitData = {}
          if (this.editModel === 'C') {
            submitData = {
              commonQuestionContent: this.ruleForm.commonQuestionContent,
              periods: this.form.periods,
              projectId: this.form.projectId,
              projectName: this.form.projectName,
              traceUserId: this.ruleForm.traceUserId,
              commQstCdsList: this.sourceData
            }
            this.assetpkgmgrFullScreenLoading()
            this.createQustApi.defaultSave(submitData).then(res => {
              this.assetpkgmgrFullScreenLoading().close()
              if (res.success) {
                this.success('新增通用问题成功')
                this.$emit('createQust', true)
                if (type === '1') {
                  this.dialogVisible = false
                } else {
                  this.ruleForm = { commonQuestionContent: '', traceUserId: '' }
                  this.sourceData2 = []
                }
              } else {
                this.warning('新增通用问题失败')
                this.$emit('createQust', true)
              }
            }).catch(res => this.assetpkgmgrFullScreenLoading().close())
          } else {
            submitData = {
              commonQuestionContent: this.ruleForm.commonQuestionContent,
              commonQuestionNo: this.commonInfo.commonQuestionNo,
              keyId: this.commonInfo.keyId,
              modifyTime: this.commonInfo.modifyTime,
              periods: this.form.periods,
              projectId: this.form.projectId,
              projectName: this.form.projectName,
              traceUserId: this.ruleForm.traceUserId,
              commQstCdsList: this.sourceData
            }
            this.assetpkgmgrFullScreenLoading()
            this.createQustApi.postDefaultUpdate(submitData).then(res => {
              this.assetpkgmgrFullScreenLoading().close()
              if (res.success) {
                this.success('变更通用问题成功')
                this.$emit('createQust', true)
                if (type === '1') {
                  this.dialogVisible = false
                }
              } else {
                this.warning('变更通用问题失败')
                this.$emit('createQust', true)
              }
            }).catch(res => this.assetpkgmgrFullScreenLoading().close())
          }
        } else {
          this.error('表单填写错误')
        }
      })
    },
    // 保存
    save () {
      if (this.sourceData.length === 0) {
        this.warning('没有要保存的数据')
      } else {
        let arr1 = this.allRelated // 原来的数据
        let arr2 = this.sourceData // 保存的数据
        arr1 = arr1.map(JSON.stringify)
        arr2 = arr2.map(JSON.stringify)
        let difData = arr1.concat(arr2).filter(function (v, i, arr) {
          return arr.indexOf(v) === arr.lastIndexOf(v)
        }).map(JSON.parse)
        if (difData.length === 0 && this.commonInfo.commonQuestionContent === this.ruleForm.commonQuestionContent &&
        this.commonInfo.traceUserId === this.ruleForm.traceUserId) {
          this.warning('没有更改的数据')
        } else {
          this.saveData('1')
        }
      }
    },
    // 保存并新建
    saveAndCreate () {
      if (this.sourceData.length === 0) {
        this.warning('没有要保存的数据')
      } else {
        this.saveData('2')
      }
    }
  },
  mounted () {
    if (this.editModel === 'E') {
      Object.assign(this.queryParas, this.form)
      Object.assign(this.queryParas, this.commonInfo)
      this.$nextTick(() => {
        this.loadEditData(this.queryParas)
      })
    } else {
      Object.assign(this.queryParas, this.form)
      this.$nextTick(() => {
        this.handleFilter()
      })
    }
  },
  computed: {
    sourceData3: function () {
      let data = this.sourceData2.slice((this.queryParas1.pageIndex - 1) * this.queryParas1.pageSize, this.queryParas1.pageIndex * this.queryParas1.pageSize)
      let newData = data.sort((a, b) => {
        return a.assetCode > b.assetCode ? 1 : -1
      })
      return newData
    },
    qustListApi () {
      return coordManageApi.getQustList
    },
    createQustApi () {
      return coordManageApi.createQust
    },
    coordPageApi () {
      return coordManageApi.getCoordInfo
    }
  }
}
</script>
<style lang="scss" scoped>
@import '~@/styles/assetoutfeedback/common.scss'
</style>
