<template>
  <div>
    <div class="suggestion-wrapper">
      <div class="label">{{this.define.title}}</div>
      <div class="input-wrapper">
        <Input v-model="value" type="textarea" :placeholder="define.config.placeholder" :maxlength="240" />
        <div class="suggestion-button-wrapper">
          <ConfirmPopover
            v-for="suggestion in suggestionOption"
            :key="suggestion.code"
            v-model="suggestion.visible"
            @cancle="suggestion.visible = false"
            @confirm="() => {handleDelete([suggestion]); suggestion.visible = false}"
          >
            <div
              class="suggestion-button"
              :style="{ background: `${themeColor}15`, border: `1px solid ${themeColor}29`}"
              v-show="suggestion.id"
              @click="handleSelectSuggestion(suggestion)"
              @mouseover="currentHoverSuggestion = suggestion"
              @mouseout="currentHoverSuggestion = null"
            >
              <div class="text" :style="{ color: themeColor }">{{suggestion.spyj}}</div>
              <div
                @click.stop="$set(suggestion, 'visible', true)"
                v-show="suggestion === currentHoverSuggestion"
                class="delete-icon"
              >
                <Icon type="md-close-circle" />
              </div>
            </div>
          </ConfirmPopover>
        </div>
        <!-- <div>
          <Button size="small" @click="suggestionOptionModal = true">edit</Button>
          <Button size="small" @click="handleAdd">add</Button>
        </div> -->
      </div>
    </div>
    <el-dialog
      v-if="suggestionOptionModal"
      title="常用意见列表"
      :visible.sync="suggestionOptionModal"
      width="60%"
      :modal="false"
      custom-class="suggestion-option-modal"
    >
      <div slot="title" class="header">
        编辑常用意见
      </div>
      <div class="suggestion-modal-toolbar">
        <div v-if="suggestionOption.length > 0">共{{suggestionOption.length}}条审批意见</div>
        <div class="button-wrapper">
          <Button style="margin-right: 5px;" size="small" @click="addNewRow">添加意见</Button>
          <Poptip
            confirm
            :transfer="true"
            title="是否删除选中项?"
            @on-ok="handleBatchDelete"
          >
            <Button size="small">批量删除</Button>
          </Poptip>
        </div>
      </div>
      <Table
        ref="suggestionTable"
        size="small"
        :columns="suggestionTableColumns"
        border
        :max-height="400"
        :data="suggestionOption"
        @on-selection-change="handleSelectionChange"
      >
        <template slot-scope="{ row }" slot="spyj">
          <div
            v-show="currentEditSuggestion.code != row.code"
            @click="handleClickRow(row)"
          >
            {{row.spyj}}
          </div>
          <Input
            v-model="currentEditSuggestion.spyj"
            v-show="currentEditSuggestion.code === row.code"
            :ref="'input-' + row.code"
            @on-blur="handleInputBlur(row)"
            type="textarea"
            :maxlength="240"
          />
        </template>
        <template slot-scope="{ row, index }" slot="action">
          <Button
            :class="index < 1 ? '' : 'suggestion-edit-button'"
            :disabled="index < 1"
            size="small"
            type="text"
            @click="setOrder(row, -1)"
          >
            上移
          </Button>
          <Button
            :class="index >= suggestionOption.length - 1 ? '' : 'suggestion-edit-button'"
            :disabled="index >= suggestionOption.length - 1"
            size="small"
            type="text"
            @click="setOrder(row, 1)"
          >
            下移
          </Button>
          <Poptip
            confirm
            :transfer="true"
            title="确定要删除本条意见吗?"
            @on-ok="handleDelete([row])"
            popper-class="suggestion-edit-table-popper"
          >
            <Button class="suggestion-edit-button" size="small" type="text">删除</Button>
          </Poptip>
        </template>
      </Table>
    </el-dialog>
  </div>
</template>

<script>
const TABLE_NAME = "MD_SPYJ"
import ConfirmPopover from './confirm-popover'
import { BILL_GLOBAL_PARAM } from '../../constant';

export default {
  name: 'ApprovalUserControl',
  components: {
    ConfirmPopover,
  },
  props: {
    define: {
      type: Object,
      required: true,
    },
    context: {
      type: Object,
      default: () => { }
    }
  },
  data() {
    return {
      value: '',
      suggestionOptionModal: false,
      reviewParam:{},
      taskId: null,
      currentEditSuggestion: {},
      suggestionOption: [],
      suggestionTableColumns: [
        {
          type: 'selection',
          width: 50,
          align: 'center',
        },
        {
          title: '序号',
          width: 60,
          align: 'center',
          key: 'index',
        },
        {
          title: '审批意见',
          slot: 'spyj',
        },
        {
          title: '操作',
          slot: 'action',
          // align: 'center',
          maxWidth: 160,
        }
      ],
      selectedSuggestion: [],
      themeColor: this.define?.config?.fontColor || '#5369D8',
      currentHoverSuggestion: null,
      currentTagId: null,
    }
  },
  watch: {
    value(newV) {
      this.reviewParam['suggestions'] = newV;
      this.context.bill.setGlobalParam(BILL_GLOBAL_PARAM.APPROVAL_COMMENT,this.reviewParam);
    }
  },
  mounted() {
    this.reviewParam['taskId'] = GMS.workflowTaskId
    this.taskId = GMS.workflowTaskId;
    // this.reviewParam['billid'] = this.$route.query.id;
    this.context.bill.setGlobalParam(BILL_GLOBAL_PARAM.APPROVAL_COMMENT,this.reviewParam);
    this.value = this.context.bill.getGlobalParam(BILL_GLOBAL_PARAM.APPROVAL_COMMENT).suggestions
    this.currentTagId = window.nros.context.getCurrTag()
    window.GMS.vbus.$on('approval-user-control-edit', this.openEditModal)
    window.GMS.vbus.$on('approval-user-control-add', this.handleAdd)
    this.getSuggestionOptions()
  },
  beforeDestroy() {
    window.GMS.vbus.$off('approval-user-control-edit', this.openEditModal)
    window.GMS.vbus.$off('approval-user-control-add', this.handleAdd)
  },
  methods: {
    showDeletePopover(suggestion) {
      this.$set(suggestion, 'visible', true)
    },
    openEditModal() {
      if (this.currentTagId && this.currentTagId != window.nros.context.getCurrTag()) return
      this.suggestionOptionModal = true
    },
    genCode() {
      return `${Date.now()}${Math.random().toString(36).slice(-8)}`
    },
    /**
     * @param {object} row
     * @param {1 | -1} direction - 1下移,-1上移
     */
    async setOrder(row, direction) {
      // index 是从1开始的,,,,
      if (
        row.index + direction > this.suggestionOption.length
        || row.index + direction <= 0
      ) return
      const neighborRow = this.suggestionOption[row.index + direction - 1]
      await window.GAMS.Util.invokeServer({
        path: 'bpm/bill/action/updateOrder',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify([row, neighborRow].map((o) => {
          const ans = {...o}
          delete ans.index
          return ans
        })),
      })
      await this.getSuggestionOptions()
    },
    addNewRow() {
      this.currentEditSuggestion = {
        code: this.genCode(),
      }
      this.suggestionOption.push(this.currentEditSuggestion)
      this.$nextTick(() => {
        this.focusInput(this.currentEditSuggestion.code)
      })
    },
    focusInput(code) {
      this.$refs[`input-${code}`] && this.$refs[`input-${code}`].focus()
    },
    handleInputBlur(row) {
      this.saveSuggestion()
    },
    handleClickRow(row) {
      this.currentEditSuggestion = row
      this.$nextTick(() => {
        this.focusInput(row.code)
      })
    },
    handleBatchDelete() {
      this.handleDelete(this.selectedSuggestion)
      this.selectedSuggestion = []
    },
    handleSelectionChange(selection) {
      this.selectedSuggestion = [...selection]
    },
    handleSelectSuggestion(s) {
      this.value = s.spyj
    },
    handleAdd() {
      if (this.currentTagId && this.currentTagId != window.nros.context.getCurrTag()) return

      this.currentEditSuggestion = {
        code: this.genCode(),
        spyj: this.value,
      }
      this.saveSuggestion()
    },
    async add() {
      this.currentEditSuggestion = {
        name: "",
        parentcode: "-",
        parentcode_show: {name: "-", title: "-"},
        shortname: "",
        stopflag: 0,
        tableName: TABLE_NAME,
        ...this.currentEditSuggestion,
      }
      await window.GAMS.Util.invokeServer({
        path: 'bpm/bill/action/add',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(this.currentEditSuggestion),
      })
    },
    async saveSuggestion() {
      if (this.currentEditSuggestion.id) {
        await this.update()
      }
      else if (this.currentEditSuggestion.spyj && this.currentEditSuggestion.spyj.trim()) {
        await this.add()
      }
      this.currentEditSuggestion = {}
      this.getSuggestionOptions()
    },
    async update() {
      delete this.currentEditSuggestion.showTitleMap
      this.currentEditSuggestion.ver = Date.now()
      await window.GAMS.Util.invokeServer({
        path: 'baseData/data/update',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(this.currentEditSuggestion),
      })
    },
    async handleDelete(s) {
      const params = {
        dataList: s,
        tableName: TABLE_NAME,
      }
      await window.GAMS.Util.invokeServer({
        path: 'baseData/data/batch/remove',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(params),
      })
      this.getSuggestionOptions()
    },
    async getSuggestionOptions() {
      const res = await window.GAMS.Util.invokeServer({
        path: 'bpm/bill/action/list',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
          "tableName": TABLE_NAME,
          "pagination": false,
          "searchKey": "",
          "queryDataStructure": "ALL_WITH_REF",
          "stopflag": -1,
          "authType": "NONE"
        }),
      })
      this.suggestionOption = (res && res.rows || []).map((o, index) => ({
        ...o,
        index: index + 1,
        tableName: TABLE_NAME,
      }))
    }
  },
}
</script>

<style lang="less">
.suggestion-wrapper {
  display: flex;
  .label {
    width: 90px;
    text-align: right;
  }
  .input-wrapper {
    flex: 1;
    padding-left: 15px;
    .suggestion-button-wrapper {
      display: flex;
      flex-wrap: wrap;
      padding-top: 12px;
      max-height: 84px;
      overflow: hidden;
      .suggestion-button {
        cursor: pointer;
        height: 28px;
        padding: 0px 11px;
        margin: 0px 8px 8px 0px;
        border-radius: 3px;
        position: relative;
        .delete-icon {
          width: 12px;
          height: 12px;
          font-size: 10px;
          color: red;
          position: absolute;
          top: -10px;
          right: -6px;
        }
        .text {
          height: 28px;
          max-width: 140px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          font-size: 14px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          line-height: 28px;
        }
      }
    }
  }
}
.suggestion-edit-table-popper[style] {
  z-index: 3000 !important;
}
.suggestion-option-modal {
  .header {
    text-align: left;
    height: 22px;
    font-size: 16px;
    font-weight: 500;
    color: #0F0F0F;
    line-height: 22px;
  }
  .el-dialog__header {
    border-bottom: 1px solid #e5e5e5;
  }
  .el-dialog__body {
    overflow-y: scroll;
    padding-top: 20px;
    .suggestion-modal-toolbar {
      padding-bottom: 4px;
      display: flex;
      justify-content: space-between;
      .button-wrapper {
        flex: 1;
        display: flex;
        justify-content: flex-end;
      }
    }
    .ivu-table-header thead tr th {
      padding: 5px 0px;
    }
    .ivu-table-small td {
      padding: 5px 0px;
    }
    .ivu-table-cell {
      padding: 0 10px;
    }
    .suggestion-edit-button {
      color: #5369D8;
    }
    
  }
}
</style>