<template>
  <div>
    <a-modal
      class="modalBox"
      :footer="null"
      title="选择考评项"
      v-model="isshow"
      @cancle="cancel"
      :width="'80%'">
      <a-row :gutter="24">
        <a-col class="title" :span="20">
          <!-- 考评方案名称 -->
          <span>考评方案名称: {{ itemName }}</span>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-form :form="form" ref="form" @submit="handleSubmit">
          <a-card class="card-content">
            <a-col :span="15">
              <p>已选考评项目：</p>
              <!-- 已选考评项列表 -->
              <a-table
                ref="table"
                size="default"
				:scroll={y:500}
                :pagination="false"
                :rowKey="(record) => record.id"
                :columns="columns"
                :dataSource="checkedList"
                bordered>
                <!-- 操作 -->
                <template slot="action" slot-scope="text, record, index">
                  <a-button
                    id="setEvaModal-moveUp"
                    type="primary"
                    ghost
                    size="small"
                    class="actionBtn"
                    @click="moveUp(index)"
                    v-if="index>0"
                    icon="arrow-up">上移</a-button>
                  <a-button
                    id="setEvaModal-moveDown"
                    type="primary"
                    ghost
                    size="small"
                    class="actionBtn"
                    @click="moveDown(index)"
                    v-if="index < checkedList.length-1"
                    icon="arrow-down">下移</a-button>
                  <a-button
                    id="setEvaModal-moveTop"
                    type="danger"
                    ghost
                    size="small"
                    class="actionBtn"
                    @click="moveTop(index)"
                    v-if="index>0"
                    icon="up">置顶</a-button>
                  <a-button
                    id="setEvaModal-moveBottom"
                    type="danger"
                    ghost
                    size="small"
                    class="actionBtn"
                    @click="moveBottom(index)"
                    v-if="index < checkedList.length-1"
                    icon="down">置底</a-button>
                </template>
              </a-table>

            </a-col>
            <a-col span="1" class="divider">
            </a-col>
            <a-col span="8">
              <a-row>
                <p>请选择需要的考评项目：</p>
              </a-row>
              <s-table
                ref="tableItem"
                size="default"
				:scroll={y:500}
                :showPagination="false"
                :row-selection="rowSelection"
                :rowKey="(record) => record.id"
                :columns="itemColumns"
                :data="loadItemData"
                bordered>
                <!-- 启用禁用 -->
                <template slot="enable" slot-scope="text, row">
                  <span :class="[text==1 ? 'green' : 'grey']">{{ text==1 ? '启用' : '禁用' }}</span>
                </template>
              </s-table>
            </a-col>
          </a-card>
          <a-form-item class="footer" :wrapper-col="{ span: 24, offset: 12 }">
            <a-button :loading="loading" id="setEvaModal-submit" type="primary" @click="handleSubmit()">
              保存
            </a-button>
            <a-button id="setEvaModal-cancel" :style="{ marginLeft: '8px' }" @click="cancel()">
              取消
            </a-button>
          </a-form-item>
        </a-form>
      </a-row>

    </a-modal>
  </div>
</template>

<script>
import {
  STable,
  VSelect
} from '@/components'
import {
  planItemQuery,
  planItemSave
} from '@/api/evaluationPlan.js'
import { getItemList } from '@/api/evaluationItem.js'
export default {
  name: 'AddEvaModal',
  components: {
    STable,
    VSelect
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    // 要编辑的方案id
    itemId: {
      type: [String, Number],
      default: ''
    },
    // 要编辑的方案名字
    itemName: {
	  type: String,
	  default: ''
    }
  },
  watch: {
    visible (newValue, oldValue) {
      this.isshow = newValue
    },
    isshow (newValue, oldValue) {
      if (newValue) {
        // 获取已选列表数据
        this.getCheckedList()
      } else {
        this.cancel()
      }
    }
  },
  data () {
    return {
      isshow: this.visible, // 弹框显示隐藏
      form: this.$form.createForm(this, {
        name: 'SetEvaModal'
      }),
	  loading: false, // 确定按钮loading
      // 已选考评项数据
      checkedList: [], // 已选考评项列表
      // 表头
      columns: [{
        title: '序号',
        dataIndex: 'no',
        width: '40',
        align: 'center'
      },
      {
        title: '考评项目名称',
        dataIndex: 'assessItemName',
        align: 'center'
      },
      {
        title: '操作',
        width: '200',
        align: 'center',
        scopedSlots: {
          customRender: 'action'
        }
      }
      ],
      // 考评项列表数据
      itemColumns: [{
        title: '考评项目名称',
        dataIndex: 'name',
        align: 'center'
      },
      {
        title: '状态',
        width: '200',
        dataIndex: 'status',
        align: 'center',
        scopedSlots: {
          customRender: 'enable'
        }
      }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadItemData: parameter => {
        return getItemList().then(res => {
          if (res.status == 200) {
            return res.data
          }
        })
      }
    }
  },
  computed: {
    // 已选择的复选框
    selectedRowKeys () {
      const arr = []
      this.checkedList.map(item => {
        arr.push(item.assessItemId)
      })
      return arr
    },
    // 列表项是否可选择的配置
    rowSelection () {
      return {
        columnTitle: '选择', // 选择框标题
        columnWidth: 80, // 选择框宽度
        selectedRowKeys: this.selectedRowKeys, // 指定选中项的 key 数组
        // 选中项发生变化时的回调 selectedRowKeys：指定选中项的 key 数组 selectedRows：已选中的数组数据
        onChange: (selectedRowKeys, selectedRows) => {
          const arr = []
          let index = 0
  		  // 根据选择项的顺序展示已选列表
          selectedRowKeys.map(item => {
            index++
            const p = selectedRows.find(row => row.id == item)
            const row = {}
            if (p) {
              row.no = index
			  row.assessItemId = p.id
			  row.assessItemName = p.name
			  row.assessSchemeId = this.itemId
              arr.push(row)
            }
          })
          this.checkedList = arr
          // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
        },
        getCheckboxProps: record => ({
          props: {
            disabled: record.status == '0' // 禁用状态不可选
          }
        })
      }
    }
  },
  methods: {
    // 获取已选列表数据
    getCheckedList () {
      planItemQuery({ assessSchemeId: this.itemId }).then(res => {
        if (res.status == 200) {
          this.checkedList = res.data
          this.checkedList.map((item, index) => {
            item.no = index + 1
          })
        } else {
          this.checkedList = []
          this.$message.warning(res.message)
        }
      })
    },
    // 点击弹框x号触发事件
    cancel (e) {
      this.clear()
      this.$emit('close')
    },
    // 上移
    moveUp (index) {
      this.moveArr(index, index - 1)
    },
    // 下移
    moveDown (index) {
      this.moveArr(index, index + 1)
    },
    // 置顶
    moveTop (index) {
      this.goToArr(index, 1)
    },
    // 置底
    moveBottom (index) {
      this.goToArr(index, 0)
    },
    // 置顶和置底
    goToArr (index, type) {
      const arr = this.checkedList
      const row = arr[index]
      arr.splice(index, 1)
      if (type) {
        arr.unshift(row)
      } else {
        arr.push(row)
      }
      arr.map((item, index) => {
        item.no = index + 1
      })
    },
    // 移动
    moveArr (index1, index2) {
      const arr = this.checkedList
      arr[index1] = arr.splice(index2, 1, arr[index1])[0]
      arr.map((item, index) => {
        item.no = index + 1
      })
      this.checkedList = arr
    },
    // 保存提交
    handleSubmit () {
      const _this = this
      this.form.validateFields((err, values) => {
        if (!err) {
          if (!this.checkedList.length) {
            return this.$message.warning('请先选择考评项目')
          }
		  this.loading = true
          planItemSave(this.checkedList).then(res => {
            console.log(res, 'res--save')
            if (res.status + '' === '200') {
              this.$message.success(res.message ? res.message : '保存成功')
              this.$emit('refresh')
              setTimeout(function () {
                _this.cancel()
              }, 300)
            } else {
              // this.$message.warning(res.message)
            }
            this.loading = false
          })
        }
      })
    },
    // 取消
    handleCancel () {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确定取消吗?',
        okText: '确定',
        cancelText: '取消',
        onOk () {
          _this.clear()
          _this.cancel()
        }
      })
    },
    clear () {
      this.form.resetFields()
    }

  },
  beforeCreate () {
    this.form = this.$form.createForm(this, {
      name: 'SetEvaModal'
    })
  }

}
</script>

<style scoped>
	.title {
		font-size: 16px;
		color: black;
		padding-bottom: 30px;
	}
	.actionBtn {
		font-size: 12px;
		margin: 0 5px;
	}

	.green {
		color: #16b50e;
	}

	.grey {
		color: rgb(153, 153, 153);
	}

	.footer {
		margin-top: 20px;
	}
</style>
