<template>
  <div style="height:600px;overflow-y:auto;">
    <div class="from-table" style="margin-top:12px">
      <a-row>
        <a-col :span="2" class="bg-gray">
          评审名称
        </a-col>
        <a-col :span="10">
          {{evaluation.name}}
        </a-col>
        <a-col :span="2" class="bg-gray">
          总分
        </a-col>
        <a-col :span="2">
          {{evaluation.score}}
        </a-col>
        <a-col :span="8">
          <a-button type="primary" size="small" @click="addEvalContent()">添加评审内容</a-button>
        </a-col>
      </a-row>
    </div>
    <a-divider style="height: 1px; background-color: #e8e8e8;" />
    <a-collapse :activeKey="activeKey1" accordion :expand-icon-position="expandIconPosition" icon="setting" @change="changeActivekey">
      <a-collapse-panel v-for="content in evaluationContents" :key="content.id" :header="content.name + ' (' + content.score + '分)'">
        <a-switch slot="extra" checked-children="有" un-checked-children="无" :checked="checkedState(content)" @change="switchChange($event,content)" />
        <a-radio-group slot="extra" v-model="content.valueType" style="margin-left: 10px;" v-if="!content.hasSubitem" @change="radioGroupChange($event,content)">
          <a-radio :value="1">单选</a-radio>
          <a-radio :value="2">多选</a-radio>
          <a-radio :value="3">打分</a-radio>
        </a-radio-group>
        <a-button slot="extra" type="primary" size="small" @click="modEvalContent(content.id)" style="margin-left: 10px;">修改</a-button>
        <a-button slot="extra" type="primary" size="small" @click="delEvalContent(content)" style="margin-left: 10px;">删除</a-button>
        <a-button slot="extra" type="primary" size="small" @click="addContentItem($event, content.id)" style="margin-left: 10px;" v-if="content.hasSubitem">添加子项</a-button>
        <a-button slot="extra" type="primary" size="small" @click="addContentValue($event, content)" style="margin-left: 10px;" v-if="(!content.hasSubitem && content.valueType == 1) || (!content.hasSubitem && content.valueType == 2)">添加评审项值</a-button>

        <a-collapse :activeKey="activeKey2" accordion :expand-icon-position="expandIconPosition" icon="setting" v-if="content.hasSubitem">
          <a-collapse-panel v-for="item in content.contentItems" :key="item.id" :header="item.name + ' (' + item.score + '分)'">
            <a-radio-group slot="extra" v-model="item.valueType" style="margin-left: 10px;" @change="radioGroupValueChange($event,item)">
              <a-radio :value="1">单选</a-radio>
              <a-radio :value="2">多选</a-radio>
              <a-radio :value="3">打分</a-radio>
            </a-radio-group>
            <a-button slot="extra" type="primary" size="small" @click="modContentItem(item.id)">修改</a-button>
            <a-button slot="extra" type="primary" size="small" @click="delContentItem(item)" style="margin-left: 10px;">删除</a-button>
            <a-button slot="extra" type="primary" size="small" @click="addItemValue($event, item)" style="margin-left: 10px;" v-if="item.valueType == 1 || item.valueType == 2">添加评审项值</a-button>

            <a-table :dataSource="item.itemValues" :columns="columns" rowKey="id" :pagination="false" :loading="loading" size="small" bordered v-if="item.valueType == 1 || item.valueType == 2">
              <template v-for="col in ['name', 'score', 'showIndex', 'remark']" :slot="col" slot-scope="text, record, index">
                <div :key="col">
                  <a-input v-if="record.editable && (col === 'name' || col === 'remark')" style="margin: -5px 0" :value="text" @change="e => handleItemValueChange(e.target.value, record, col)" />
                  <a-input-number v-if="record.editable && col === 'score'" style="margin: -5px 0" v-model="record.score" :min="0" :step="0.5" :max="content.score" :precision="1" @change="e => onNumberItemValueChange(e, record, col)" />
                  <a-input-number v-if="record.editable && col === 'showIndex'" style="margin: -5px 0" v-model="record.showIndex" :min="1" :step="1" @change="e => onNumberItemValueChange(e, record, col)" />
                  <template v-if="!record.editable">{{ text }}</template>
                </div>
              </template>
              <template slot="operation" slot-scope="text, record, index">
                <div class="editable-row-operations">
                  <span v-if="record.editable">
                    <a @click="() => saveItemValue(item.contentId, record)">保存</a>
                    <a-popconfirm title="确定取消吗?" @confirm="() => cancelItemValue(record)">
                      <a>&nbsp;取消</a>
                    </a-popconfirm>
                  </span>
                  <span v-else>
                    <a :disabled="editingKey2 !== ''" @click="() => editItemValue(record)">编辑</a>&nbsp;
                    <a :disabled="editingKey2 !== ''" @click="() => deleteItemValue(record)">删除</a>
                  </span>
                </div>
              </template>
            </a-table>

            <a-tag color="cyan" v-if="item.valueType == 3">
              <a-icon type="tags" />&nbsp;{{item.remark}}
            </a-tag>
          </a-collapse-panel>
        </a-collapse>

        <a-table :dataSource="content.contentValues" :columns="columns" rowKey="id" :pagination="false" :loading="loading" size="small" bordered v-if="(!content.hasSubitem && content.valueType == 1) || (!content.hasSubitem && content.valueType == 2)">
          <template v-for="col in ['name', 'score', 'showIndex', 'remark']" :slot="col" slot-scope="text, record, index">
            <div :key="col">
              <a-input v-if="record.editable && (col === 'name' || col === 'remark')" style="margin: -5px 0" :value="text" @change="e => handleChange(e.target.value, record, col)" />
              <a-input-number v-if="record.editable && col === 'score'" style="margin: -5px 0" v-model="record.score" :min="0" :step="0.5" :max="content.score" :precision="1" @change="e => onNumberChange(e, record, col)" />
              <a-input-number v-if="record.editable && col === 'showIndex'" style="margin: -5px 0" v-model="record.showIndex" :min="1" :step="1" @change="e => onNumberChange(e, record, col)" />
              <template v-if="!record.editable">{{ text }}</template>
            </div>
          </template>
          <template slot="operation" slot-scope="text, record, index">
            <div class="editable-row-operations">
              <span v-if="record.editable">
                <a @click="() => saveContentValue(record)">保存</a>
                <a-popconfirm title="确定取消吗?" @confirm="() => cancelContentValue(record)">
                  <a>&nbsp;取消</a>
                </a-popconfirm>
              </span>
              <span v-else>
                <a :disabled="editingKey1 !== ''" @click="() => editContentValue(record)">编辑</a>&nbsp;
                <a :disabled="editingKey1 !== ''" @click="() => deleteContentValue(record)">删除</a>
              </span>
            </div>
          </template>
        </a-table>

        <a-tag color="cyan" v-if="(!content.hasSubitem && content.valueType == 3)">
          <a-icon type="tags" />&nbsp;{{content.remark}}
        </a-tag>
      </a-collapse-panel>
    </a-collapse>
    <a-modal v-model="evalContentVisible" title="评审内容编辑" width="600px" :footer="null" destroyOnClose>
      <evaluation-content-edit v-model="Id" :evaluationId="evaluationId" :currentScore="currentScore" :totalScore="totalScore" :totalCount="totalCount" :editType="editType" @close="closeEvalContentWindow"></evaluation-content-edit>
    </a-modal>
    <a-modal v-model="contentItemVisible" title="内容子项编辑" width="600px" :footer="null" destroyOnClose>
      <evaluation-content-item-edit v-model="Id" :contentId="contentId" :currentScore="currentScore" :totalScore="totalScore" :totalCount="totalCount" :editType="editType" @close="closeContentItemWindow"></evaluation-content-item-edit>
    </a-modal>
  </div>
</template>

<script>
import { isEmptyParams, CreateUUID } from '@/views/utils/common'
import EvaluationContentEdit from '@/views/system/evaluation/evaluationContentEdit'
import EvaluationContentItemEdit from '@/views/system/evaluation/evaluationContentItemEdit'

const tableData = [];

export default {
  name: 'EvaluationContent',
  components: {
    EvaluationContentEdit,
    EvaluationContentItemEdit,
  },
  props: {
    value: {
      type: String,
      default: () => {
        return null
      },
    },
  },
  data () {
    this.cacheData = tableData.map(item => ({ ...item }));
    return {
      evaluation: {
        id: null,
        name: null,
        score: 1,
        remark: ''
      },
      expandIconPosition: 'left',
      evalContentVisible: false,
      Id: null,
      evaluationId: null,
      editType: '',
      evaluationContents: [],
      totalCount: 1,
      contentId: null,
      contentItemVisible: false,
      contentItems: [],
      activeKey1: [],
      activeKey2: [],
      totalScore: 0,
      currentScore: 0,
      tableData: [],
      columns: [
        { title: '值名称', dataIndex: 'name', align: 'center', scopedSlots: { customRender: 'name' }, width: '25%' },
        { title: '总分', dataIndex: 'score', align: 'center', scopedSlots: { customRender: 'score' }, width: '10%' },
        { title: '序号', dataIndex: 'showIndex', align: 'center', scopedSlots: { customRender: 'showIndex' }, width: '10%' },
        { title: '备注', dataIndex: 'remark', align: 'center', scopedSlots: { customRender: 'remark' }, width: '30%' },
        { title: '操作', scopedSlots: { customRender: 'operation' }, align: 'center', width: '25%' },
      ],
      loading: false,
      editingKey1: '',
      editingKey2: '',
    }
  },
  created () {
    this.getEvaluationById()
    this.getEvaluationContentByEvalId()
  },
  methods: {
    getEvaluationById () {
      let par = { id: this.value }
      this.$api.systemManage.getEvaluationById(par).then(({ data = {} }) => {
        if (data) {
          this.evaluation = data
        }
      }).catch(() => { })
    },
    getEvaluationContentByEvalId () {
      let par = { id: this.value }
      this.$api.systemManage.getEvaluationContentByEvalId(par).then(({ data = {} }) => {
        if (data) {
          this.evaluationContents = data
        }
      }).catch(() => { })
    },
    changeActivekey (key) {
  
    },
    calculateContentTotalScore () {
      this.totalScore = this.evaluation.score
      this.currentScore = 0
      this.evaluationContents.forEach(p => {
        this.currentScore += p.score
      })
    },
    addEvalContent () {
      this.evaluationId = this.value
      this.totalCount = this.evaluationContents.length + 1
      this.calculateContentTotalScore()
      this.editType = 'add'
      this.evalContentVisible = true
      this.activeKey1 = this.value
    },
    modEvalContent (Id) {
      this.Id = Id
      this.evaluationId = this.value
      this.totalCount = this.evaluationContents.length + 1
      this.calculateContentTotalScore()
      this.editType = 'edit'
      this.evalContentVisible = true
      this.activeKey1 = this.value
    },
    delEvalContent (content) {
      let That = this
      this.$confirm({
        title: '删除',
        content: '确定要删除该评审内容项?',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk () {
          let pars = isEmptyParams(content)
          let par = {
            ...pars
          }
          That.$api.systemManage.deleteEvaluationContent(par).then(({ data = {} }) => {
            if (data) {
              const strArray = data.split('|')
              if (strArray[0] == 0) {
                That.$message.info(strArray[1])
              } else {
                That.getEvaluationContentByEvalId()
                That.$message.success('删除成功!')
              }
            }
          })
        },
        onCancel () {

        },
      })
    },
    closeEvalContentWindow () {
      this.evalContentVisible = false
      this.getEvaluationContentByEvalId()
    },
    calcutateItemTotalScore (ContentId) {
      let content = this.evaluationContents.filter(p => p.id === ContentId)[0]
      this.totalScore = content.score
      this.currentScore = 0
      content.contentItems.forEach(c => {
        this.currentScore += c.score
      })
    },
    addContentItem (event, ContentId) {
      if (this.activeKey1 != null)
        event.stopPropagation()
      else
        this.activeKey1 = [ContentId]

      this.calcutateItemTotalScore(ContentId)
      this.activeKey1 = this.value
      if (this.currentScore >= this.totalScore) {
        this.$message.info('内容子项学分总和已经大于等于评审内容项学分,不能再添加内容子项!')
        return
      }

      this.contentId = ContentId
      let content = this.evaluationContents.filter(p => p.id === ContentId)
      this.totalCount = content[0].contentItems.length + 1
      this.editType = 'add'
      this.contentItemVisible = true
    },
    modContentItem (Id) {
      this.Id = Id
      this.editType = 'edit'
      this.contentItemVisible = true
    },
    delContentItem (Item) {
      let That = this
      this.$confirm({
        title: '删除',
        content: '确定要删除该内容子项?',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk () {
          let pars = isEmptyParams(Item)
          let par = {
            ...pars
          }
          That.$api.systemManage.deleteEvaluationItem(par).then(({ data = {} }) => {
            if (data) {
              That.getEvaluationContentByEvalId()
              That.$message.success('删除成功!')
            }
          })
        },
        onCancel () {

        },
      })
    },
    closeContentItemWindow () {
      this.contentItemVisible = false
      this.getEvaluationContentByEvalId()
    },
    checkedState (record) {//单位状态
      return record.hasSubitem ? true : false
    },
    switchChange (checked, record) {//启用/停用单位开关
      if (checked) {
        record.hasSubitem = true
        record.valueType = 0
      } else {
        record.hasSubitem = false
        record.valueType = 1
      }

      let pars = isEmptyParams(record)
      let par = { ...pars }
      this.$api.systemManage.CheckContentHasItemsOrValues(par).then(({ data = {} }) => {
        if (data) {
          const strArray = data.split('|')
          if (strArray[0] == 0) {
            this.$message.info(strArray[1])
            record.hasSubitem = !record.hasSubitem
          }
          else {
            this.$api.systemManage.updateEvaluationContent(par).then(({ data = {} }) => {
              if (data) {
                this.$message.info(data)
              }
            }).catch(() => { })
          }
        }
      }).catch(() => { })
    },
    radioGroupChange (event, record) {
      let pars = isEmptyParams(record)
      let par = { ...pars }

      if (record.valueType == 3) {
        this.$api.systemManage.CheckContentHasValues(par).then(({ data = {} }) => {
          if (data) {
            const strArray = data.split('|')
            if (strArray[0] == 0) {
              this.$message.info(strArray[2])
              record.valueType = parseInt(strArray[1])
            } else {
              this.ModifyEvaluationContent(record)
            }
          }
        }).catch(() => { })
      } else {
        this.ModifyEvaluationContent(record)
      }
    },
    ModifyEvaluationContent (record) {
      let pars = isEmptyParams(record)
      let par = { ...pars }
      this.$api.systemManage.updateEvaluationContent(par).then(({ data = {} }) => {
        if (data) {
          this.$message.info(data)
        }
      }).catch(() => { })
    },
    handleChange (value, record, column) {
      record[column] = value
    },
    onNumberChange (value, record, column) {
      if (column === 'score')
        record.score = value
      else
        record.showIndex = value
      this.activeKey1 = [record.objectId]
    },
    editContentValue (CValue) {
      this.editingKey1 = CValue.key
      CValue.editable = true
      this.activeKey1 = [CValue.objectId]
    },
    deleteContentValue (CValue) {
      let That = this
      this.$confirm({
        title: '删除',
        content: '确定要删除该子项?',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk () {
          let pars = isEmptyParams(CValue)
          let par = {
            ...pars
          }
          That.$api.systemManage.deleteEvaluationValue(par).then(({ data = {} }) => {
            if (data) {
              That.getEvaluationContentByEvalId()
              That.$message.success('删除成功!')
            }
          })
        },
        onCancel () {

        },
      })
    },
    cancelContentValue (CValue) {
      this.editingKey1 = ''
      CValue.editable = false
      this.activeKey1 = [CValue.objectId]
    },
    calContentValueTotalScore (contentId, flag) {
      const content = this.evaluationContents.filter(item => contentId === item.id)[0]
      if (content.contentValues === undefined || content.contentValues === null)
        return true

      this.currentScore = 0
      content.contentValues.forEach(p => {
        this.currentScore += p.score
      })
      if (flag) {
        if (this.currentScore > content.score)
          return false
        else
          return true
      } else {
        if (this.currentScore >= content.score)
          return false
        else
          return true
      }
    },
    saveContentValue (CValue) {
      this.editingKey1 = ''
      CValue.editable = false
      this.activeKey1 = [CValue.objectId]

      if (!this.calContentValueTotalScore(CValue.objectId, true)) {
        this.$message.info('值分数总和已经超出评审内容分数!')
        return
      }

      let pars = isEmptyParams(CValue)
      let par = { ...pars }
      if (CValue.hasAdd == 1) {
        this.$api.systemManage.updateEvaluationValue(par).then(({ data = {} }) => {
          if (data) {
            this.$message.info(data)
          }
        }).catch(() => { })
      } else {
        this.$api.systemManage.insertEvaluationValue(par).then(({ data = {} }) => {
          if (data) {
            this.$message.info(data)
          }
        }).catch(() => { })
      }
      CValue.hasAdd = 1
    },
    addContentValue (event, content) {
      // if (!this.calContentValueTotalScore(content.id, false)) {
      //   this.$message.info('值分数总和已经超出评审内容分数!')
      //   return
      // }
      if (this.activeKey1 != null)
        event.stopPropagation()
      else
        this.activeKey1 = [content.id]

      if (content.contentValues === undefined || content.contentValues === null)
        content.contentValues = []

      let count = 1
      if (content.contentValues.length > 0)
        count = content.contentValues.length + 1

      let ID = CreateUUID()
      content.contentValues.push({
        id: ID,
        key: ID,
        objectId: content.id,
        hasAdd: 0,
        name: '',
        score: 0,
        showIndex: count,
        remark: ''
      })
    },
    radioGroupValueChange (event, record) {
      let pars = isEmptyParams(record)
      let par = { ...pars }
      if (record.valueType == 3) {
        this.$api.systemManage.CheckItemHasValues(par).then(({ data = {} }) => {
          if (data) {
            const strArray = data.split('|')
            if (strArray[0] == 0) {
              this.$message.info(strArray[2])
              record.valueType = parseInt(strArray[1])
            } else {
              this.ModifyEvaluationItem(record)
            }
          }
        }).catch(() => { })
      } else {
        this.ModifyEvaluationItem(record)
      }
    },
    ModifyEvaluationItem (record) {
      let pars = isEmptyParams(record)
      let par = { ...pars }
      this.$api.systemManage.updateEvaluationItem(par).then(({ data = {} }) => {
        if (data) {
          this.$message.info(data)
        }
      }).catch(() => { })
    },
    handleItemValueChange (value, record, column) {
      record[column] = value
    },
    onNumberItemValueChange (value, record, column) {
      if (column === 'score')
        record.score = value
      else
        record.showIndex = value
      this.activeKey2 = [record.objectId]
    },
    addItemValue (event, item) {
      // if (!this.calItemValueTotalScore(item.objectId, item.id, false)) {
      //   this.$message.info('值分数总和已经超出评审内容子项分数!')
      //   return
      // }
      if (this.activeKey2 != null)
        event.stopPropagation()

      if (item.itemValues === undefined || item.itemValues === null)
        item.itemValues = []

      let count = 1
      if (item.itemValues.length > 0)
        count = item.itemValues.length + 1

      let ID = CreateUUID()
      item.itemValues.push({
        id: ID,
        key: ID,
        objectId: item.id,
        hasAdd: 0,
        name: '',
        score: 0,
        showIndex: count,
        remark: ''
      })
    },
    saveItemValue (contentId, CValue) {
      this.editingKey2 = ''
      CValue.editable = false
      this.activeKey2 = [CValue.objectId]

      if (!this.calItemValueTotalScore(contentId, CValue.objectId, true)) {
        this.$message.info('值分数总和已经超出评审内容子项分数!')
        return
      }

      let pars = isEmptyParams(CValue)
      let par = { ...pars }
      if (CValue.hasAdd == 1) {
        this.$api.systemManage.updateEvaluationValue(par).then(({ data = {} }) => {
          if (data) {
            this.$message.info(data)
          }
        }).catch(() => { })
      } else {
        this.$api.systemManage.insertEvaluationValue(par).then(({ data = {} }) => {
          if (data) {
            this.$message.info(data)
          }
        }).catch(() => { })
      }
      CValue.hasAdd = 1
    },
    calItemValueTotalScore (contentId, itemId, flag) {
      const content = this.evaluationContents.filter(p => contentId === p.id)[0]
      const item = content.contentItems.filter(p => itemId === p.id)[0]
      if (item.itemValues === undefined || item.itemValues === null)
        return true

      this.currentScore = 0
      item.itemValues.forEach(p => {
        this.currentScore += p.score
      })

      if (flag) {
        if (this.currentScore > item.score)
          return false
        else
          return true
      } else {
        if (this.currentScore >= item.score)
          return false
        else
          return true
      }
    },
    cancelItemValue (CValue) {
      this.editingKey2 = ''
      CValue.editable = false
      this.activeKey2 = [CValue.objectId]
    },
    editItemValue (CValue) {
      this.editingKey2 = CValue.key
      CValue.editable = true
      this.activeKey2 = [CValue.objectId]
    },
    deleteItemValue (CValue) {
      let That = this
      this.$confirm({
        title: '删除',
        content: '确定要删除该子项?',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk () {
          let pars = isEmptyParams(CValue)
          let par = {
            ...pars
          }
          That.$api.systemManage.deleteEvaluationValue(par).then(({ data = {} }) => {
            if (data) {
              That.getEvaluationContentByEvalId()
              That.$message.success('删除成功!')
            }
          })
        },
        onCancel () {

        },
      })
    },
  }
}
</script>

<style scoped>
::v-deep .ant-modal-content {
  height: 500px !important;
}
</style>