<template>
  <j-modal
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :title="title"
    :visible="visible"
    :width="width"
    cancelText="关闭"
    @cancel="handleCancel"
    @ok="handleOk">
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :label-col="labelCol" :model="model" :rules="validatorRules" :wrapper-col="wrapperCol">
        <!-- 主表单区域 -->
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="问卷名称" prop="subject">
          <a-input v-model="model.subject" placeholder="请输入问卷名称"></a-input>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="问卷类别" prop="type">
          <j-dict-select-tag v-model="model.type" dictCode="topic_type" placeholder="请选择问卷类别" type="list"
                             @change="handleChangeType" />
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="问卷描述" prop="description">
          <a-textarea v-model="model.description" placeholder="请输入问卷描述"></a-textarea>
        </a-form-model-item>
        <a-form-model-item v-if="model.type==2" :labelCol="labelCol" :wrapperCol="wrapperCol" label="总分"
                           prop="maximumScore" class="margin">
          <span>{{ model.maximumScore }}</span>
        </a-form-model-item>
        <!-- 子表单区域 -->
        <a-tabs>
          <a-tab-pane key='1' :forceRender='true' tab='题目列表'>
            <div v-if='showTips' class='ant-form-explain' style='color: #f5222d'>请选择题目!</div>
            <a-row>
              <!-- table区域-begin -->
              <div class='ant-alert ant-alert-info' style='margin-bottom: 16px;'>
                <i class='anticon anticon-info-circle ant-alert-icon'></i> 已选择 <a
                style='font-weight: 600'>{{ selectedQuestionKeys.length }}</a>项
                <a style='margin-left: 24px' @click='onClearQuestionSelected'>清空</a>
              </div>
              <a-table
                ref='table'
                :columns='columns'
                :dataSource='dataSource'
                :loading='loading'
                :pagination='ipaginationQuestion'
                :row-selection='{selectedRowKeys: selectedQuestionKeys, onChange: onSelectQuestionChange}'
                bordered
                rowKey='id'
                size='middle'
                @change='handleTableChange'>
                <!-- 字符串超长截取省略号显示 -->
                <span slot='question' slot-scope='text'>
                  <j-ellipsis :length='25' :value='text' />
                </span>
                <span slot='action' slot-scope='text, record'>
                  <a-popconfirm title='确定删除吗?' @confirm='() => handleDelete(record.id)'>
                    <a>删除</a>
                  </a-popconfirm>
                </span>
              </a-table>
            </a-row>
          </a-tab-pane>
        </a-tabs>
      </a-form-model>
    </a-spin>

  </j-modal>
</template>

<script>
import { getAction, httpAction } from '@/api/manage'
import { filterObj } from '@/utils/util'
import JDate from '@/components/jeecg/JDate'
import JEllipsis from '@/components/jeecg/JEllipsis'

export default {
  name: 'MrQuestionnaireModal',
  components: { JDate, JEllipsis },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      title: '',
      width: 800,
      visible: false,
      disableSubmit: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 21 }
      },
      confirmLoading: false,
      validatorRules: {
        subject: [
          { required: true, message: '请输入问卷名称!' }
        ],
        questionId: [
          { required: true, message: '请选择题库!' }
        ],
        type: [
          { required: true, message: '请选择问卷类型!' }
        ],
        description: [{ required: true, message: '请输入问卷描述!' }]
      },
      url: {
        add: '/publish/questionnaire/add',
        edit: '/publish/questionnaire/edit',
        // queryById: '/MrQuestionnaire/mrQuestionnaire/queryById',
        list: '/publish/question/list'
      },
      dataSource: [],
      /* 分页参数 */
      ipaginationQuestion: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      /* 排序参数 */
      isorterQuestion: {
        column: 'createTime',
        order: 'desc'
      },
      /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
      questionQueryParam: {},
      /* 筛选参数 */
      filtersQuestion: {},
      loading: false,
      selectedQuestionKeys: [],
      selectionQuestions: [],
      description: '题库列表',
      // 表头
      columns: [
        {
          title: '题目',
          align: 'center',
          dataIndex: 'question',
          key: 'question',
          scopedSlots: { customRender: 'question' }
        },
        {
          title: '题型',
          align: 'center',
          dataIndex: 'optionType_dictText'
        },
        {
          title: '答案',
          align: 'center',
          dataIndex: 'answer_dictText'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      showTips: false,
      questionParam: {}
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    }
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },
  methods: {
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      console.log(pagination)
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipaginationQuestion = pagination
      console.log(pagination)
      this.loadData(pagination.current, 1)
    },
    onSelectQuestionChange(selectedQuestionKeys, selectionQuestions) {
      console.log(selectedQuestionKeys)
      this.selectedQuestionKeys = selectedQuestionKeys
      this.selectionQuestions = selectionQuestions
      var dataSource = this.dataSource
      var maximumScore = 0
      if (this.model.type == 2) {
        if (selectionQuestions.length > 0) {
          for (var q in selectionQuestions) {
            // for (var i in dataSource) {
            //   if (selectionQuestions[q].id == dataSource[i].id) {
            //     maximumScore = this.model.maximumScore
            //   } else {
            maximumScore = maximumScore + selectionQuestions[q].score
            // }
            // }
          }
        }
      }
      this.model.maximumScore = maximumScore
    },
    onClearQuestionSelected() {
      console.log('清空数据')
      this.selectedQuestionKeys = []
      this.selectionQuestions = []
      this.model.maximumScore = 0
      console.log(this.selectionQuestions)
      console.log(this.selectedQuestionKeys)

    },
    getQuestionQueryParam() {
      //获取查询条件
      let sqp = {}
      var param = Object.assign(sqp, this.questionQueryParam, this.isorterQuestion, this.filtersQuestion)
      param.field = this.getQueryField()
      param.pageNo = this.ipaginationQuestion.current
      param.pageSize = this.ipaginationQuestion.pageSize
      return filterObj(param)
    },
    getQueryField() {
      //TODO 字段权限控制
      var str = 'id,'
      this.columns.forEach(function(value) {
        str += ',' + value.dataIndex
      })
      return str
    },
    loadData(arg, status) {
      if (arg === 1) {
        this.ipaginationQuestion.current = 1
      }
      //update-begin--Author:kangxiaolin  Date:20190905 for：[442]主子表分开维护，生成的代码子表的分页改为真实的分页--------------------
      var params = this.questionParam
      console.log(params)
      var questionId = params.questionId
      var parameter = {
        type: params.type
      }
      if (status == 1) {
        parameter = {
          type: params.type
        }
      } else {
        if (questionId != '' && questionId != undefined && questionId != null) {
          parameter = {
            id: params.questionId
          }
        }
      }
      this.questionQueryParam = parameter
      var queryParam = this.getQuestionQueryParam()//查询条件
      console.log(queryParam)
      getAction(this.url.list, queryParam).then((res) => {
        console.log(res)
        if (res.success) {
          this.dataSource = res.result.records
          var dataSource = res.result.records
          console.log(questionId)
          if (questionId != '' && questionId != undefined && questionId != null) {
            var selectedQuestionKeys = []
            var selectionQuestions = []
            if (dataSource.length > 0) {
              for (var i in dataSource) {
                selectedQuestionKeys.push(dataSource[i].id)
                selectionQuestions.push(dataSource[i])
              }
            }
            // this.selectedQuestionKeys = getArrayElement(res.result.records, 'id')
            // this.selectionQuestions = res.result.records
            this.selectedQuestionKeys = selectedQuestionKeys
            this.selectionQuestions = selectionQuestions
          }
          console.log(this.selectedQuestionKeys)
          console.log(res.result.records)
          this.ipaginationQuestion.total = res.result.total
        } else {
          this.dataSource = null
        }
      })
    },
    getOrderMain() {
      console.log('数据改变')
      // this.queryParam.questionId = questionId
      this.questionParam = Object.assign({}, this.model)
      this.loadData(1)
    },
    handleChangeType() {
      this.questionParam = Object.assign({}, this.model)
      this.loadData(1, 1)
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.selectedQuestionKeys = []
      this.selectionQuestions = []
      this.model.maximumScore = 0
    },
    handleOk() {
      const that = this
      console.log(that.model)
      that.model.questionId = that.selectedQuestionKeys.join(',')
      if (that.selectedQuestionKeys <= 0) {
        that.showTips = true
      } else {
        that.showTips = false
      }
      console.log(that.model)
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid && !that.showTips) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          httpAction(httpurl, this.model, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
            that.close()
          })
        }

      })
    },
    submitCallback() {
      this.$emit('ok')
      this.visible = false
    },
    handleCancel() {
      this.close()
    },
    add() {
      this.edit(this.modelDefault)
    },
    edit(record) {
      this.model = Object.assign({}, record)
      this.visible = true
    },
    handleDelete(id) {
      var dataSource = this.dataSource
      var selectionQuestions = this.selectionQuestions
      var selectedQuestionKeys = this.selectedQuestionKeys
      var maximumScore = this.model.maximumScore
      console.log(selectionQuestions)
      console.log(dataSource)
      if (null != dataSource && dataSource.length > 0) {
        for (var i = 0; i < dataSource.length; i++) {
          if (dataSource[i].id == id) {
            this.dataSource.splice(i, 1)
          }
        }
      }
      if (selectionQuestions.length > 0) {
        for (const j in selectionQuestions) {
          if (id == selectionQuestions[j].id) {
            if (this.model.type == 2) {
              this.model.maximumScore = maximumScore - selectionQuestions[j].score
            }
            this.selectionQuestions.splice(j, 1)
            this.selectedQuestionKeys.splice(j, 1)
          }
        }
      }
      // this.dataSource = dataSource
      // this.model.maximumScore = maximumScore
    }
  }
}
</script>

<style scoped>
.ques_list .ant-card-body {
  padding: 0 !important;
}

.margin {
  margin-bottom: 0 !important;
}
</style>