<!-- 换班消息列表 -->
<template>
  <div>
    <Row>
      <Alert show-icon style="width: 235px;display: inline-block;" type="warning">
        本月剩余换班次数：
        <strong>{{remainNums}}</strong>
      </Alert>
      <RadioGroup
        @on-change="msgTypeChange"
        style="margin-left: 8px;"
        v-model="searchForm.eventType"
      >
        <Radio :label="SHIFT_MSG_TYPE.ANNOUNCE">
          <span>公告栏</span>
        </Radio>
        <Radio :label="SHIFT_MSG_TYPE.REQ">
          <span>被请求的</span>
        </Radio>
        <Radio :label="SHIFT_MSG_TYPE.SEND">
          <span>我发出的</span>
        </Radio>
      </RadioGroup>
      <Select
        :disabled="searchLoading"
        clearable
        style="width: 166px;"
        v-if="searchForm.eventType !== SHIFT_MSG_TYPE.ANNOUNCE"
        v-model="searchForm.shiftMsgState"
      >
        <Option :key="index" :value="index + 1" v-for="(item ,index) in SHIFT_MSG_STATE">{{item}}</Option>
      </Select>
      <Button
        :loading="searchLoading"
        @click="doInitSearch"
        style="margin-left: 8px;"
        type="primary"
      >查询</Button>
    </Row>
    <br />
    <Table :columns="columns" :data="dataList" :loading="searchLoading" border></Table>
    <br />
    <Page
      :current.sync="searchForm.pageNum"
      :page-size="searchForm.pageSize"
      :total="total"
      @on-change="pageChange"
      show-total
    />
    <Modal :mask-closable="false" :title="`换班审批状态 - ${timelineStateDesc}`" v-model="showTimeline">
      <Timeline>
        <custom-timeline-item
          :date="formatDate(item.approvalTime)"
          :key="index"
          :passed="item.map.status === '审批中'?false: (index !== timelineList.length - 1 && item.map.status !== '审批中') || (index === timelineList.length - 1 &&  (timelineState !==1 && timelineState !==3 && timelineState !==4))"
          :roleName="item.map.linkType"
          :state="item.map.status"
          :username="item.map.linkOperateName"
          v-for="(item, index) in timelineList"
        />
      </Timeline>
      <div slot="footer">
        <Button @click="showTimeline=false" type="primary">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import { SHIFT_MSG_STATE, SHIFT_MSG_TYPE, SHIFT_WAY } from '@conf/dict'
import commonList from '@/mixin/commonList'
import timeline from '@/mixin/timeline'
import TradeProposalAPI from '@api/common/tradeProposal'
import cloneDeep from 'lodash/cloneDeep'
export default {
  name: 'msg-list',
  mixins: [commonList, timeline],
  data () {
    return {
      SHIFT_MSG_STATE: SHIFT_MSG_STATE,
      SHIFT_MSG_TYPE: SHIFT_MSG_TYPE,
      SHIFT_WAY: SHIFT_WAY,
      searchForm: {
        pageNum: 1,
        pageSize: this.$config.PAGE_SIZE,
        eventType: SHIFT_MSG_TYPE.ANNOUNCE,
        shiftMsgState: null
      },
      remainNums: null,
      respConfirm: false,
      respLoading: false,
      columns: [],
      dataList: [],
      columnsAnnounce: [
        {
          type: 'index',
          title: '序号',
          width: 65,
          align: 'center'
        },
        {
          title: '业务小组',
          key: 'teamName',
          minWidth: 120
        },
        {
          title: '姓名',
          key: 'userName'
        },
        {
          title: '工号',
          key: 'userCode'
        },
        {
          title: '班次类型',
          key: 'wmName'
        },
        {
          title: '换班请求日期',
          key: 'changeDate'
        },
        {
          title: '发布日期',
          key: 'createtime'
        },
        {
          title: '操作',
          key: 'action',
          width: 150,
          render: (h, params) => {
            const uuid = params.row.uuid
            const shiftObjectId = params.row.shiftObjectId
            return h('div', [
              h(
                'Poptip',
                {
                  props: {
                    confirm: true,
                    transfer: true,
                    title: '确定响应换班吗？'
                  },
                  on: {
                    'on-ok': () => {
                      this.responseBoardConfirm(
                        uuid,
                        shiftObjectId,
                        SHIFT_MSG_TYPE.ANNOUNCE,
                        1
                      )
                    }
                  }
                },
                [
                  h(
                    'Button',
                    {
                      props: {
                        type: 'info',
                        size: 'small'
                      }
                    },
                    '响应'
                  )
                ]
              )
            ])
          }
        }
      ],
      dataAnnounce: [],
      columnsReq: [
        {
          type: 'index',
          title: '序号',
          width: 65,
          align: 'center'
        },
        {
          title: '业务小组',
          minWidth: 120,
          key: 'teamName'
        },
        {
          title: '姓名',
          key: 'userName'
        },
        {
          title: '工号',
          key: 'userCode',
          tooltip: true
        },
        {
          title: '换班请求日期',
          key: 'changeDate',
          minWidth: 20
        },
        {
          title: '班次类型',
          key: 'event'
        },
        {
          title: '发布日期',
          key: 'createtime'
        },
        {
          title: '换班方式',
          key: 'changeType'
        },
        {
          title: '状态',
          align: 'center',
          width: 120,
          render: (h, params) => {
            const row = params.row
            return h(
              'Button',
              {
                props: {
                  type: 'primary',
                  ghost: true,
                  size: 'small'
                },
                on: {
                  click: () => {
                    const relatedId = row.uuid
                    const shiftObjectId = row.shiftObjectId
                    this.timelineState = row.status
                    this.timelineStateDesc = row.chinaStatus
                    this.showTimelineList(relatedId, 1, shiftObjectId)
                  }
                }
              },
              row.chinaStatus
            )
          }
        },
        {
          title: '操作',
          key: 'action',
          width: 130,
          render: (h, params) => {
            const uuid = params.row.uuid
            const shiftObjectId = params.row.shiftObjectId
            // 换班方式（1:指定，2:非指定）
            const changeType = params.row.changeTypeValue
            // 审批状态(见src/config/dict.js > SHIFT_MSG_STATE)
            const status = params.row.status
            // 换班接受者的操作状态（1:待响应，2:已同意，3:已拒绝）
            // const reciveStatus = params.row.reciveStatus
            // 非指定有意向时有值
            // const intention = params.row.intention
            // 换班请求列表是否允许撤销 0可以撤销 非0不允许撤销
            const isCancel = params.row.isCancel
            return h('div', [
              h(
                'Poptip',
                {
                  directives: [
                    {
                      name: 'show',
                      value: changeType === SHIFT_WAY.DESINATION && status === 1
                    }
                  ],
                  props: {
                    confirm: true,
                    transfer: true,
                    title: '确定与他换班吗？'
                  },
                  on: {
                    'on-ok': () => {
                      this.responseBoardConfirm(
                        uuid,
                        shiftObjectId,
                        SHIFT_MSG_TYPE.REQ,
                        1
                      )
                    }
                  }
                },
                [
                  h(
                    'Button',
                    {
                      props: {
                        type: 'success',
                        size: 'small'
                      }
                    },
                    '同意'
                  )
                ]
              ),
              h(
                'Poptip',
                {
                  directives: [
                    {
                      name: 'show',
                      value: changeType === SHIFT_WAY.DESINATION && status === 1
                    }
                  ],
                  props: {
                    confirm: true,
                    transfer: true,
                    title: '确定拒绝该换班吗？'
                  },
                  on: {
                    'on-ok': () => {
                      this.responseBoardConfirm(
                        uuid,
                        shiftObjectId,
                        SHIFT_MSG_TYPE.REQ,
                        2
                      )
                    }
                  }
                },
                [
                  h(
                    'Button',
                    {
                      style: {
                        'margin-left': '4px'
                      },
                      props: {
                        type: 'error',
                        size: 'small'
                      }
                    },
                    '拒绝'
                  )
                ]
              ),
              h(
                'Poptip',
                {
                  directives: [
                    {
                      name: 'show',
                      value: status === 4 && isCancel === 0
                    }
                  ],
                  props: {
                    confirm: true,
                    transfer: true,
                    title: '确定撤销换班吗？'
                  },
                  on: {
                    'on-ok': () => {
                      this.responseBoardConfirm(
                        uuid,
                        shiftObjectId,
                        SHIFT_MSG_TYPE.REQ,
                        3
                      )
                    }
                  }
                },
                [
                  h(
                    'Button',
                    {
                      props: {
                        type: 'warning',
                        size: 'small'
                      }
                    },
                    '撤销'
                  )
                ]
              )
            ])
          }
        }
      ],
      dataReq: [],
      columnsSend: [
        {
          type: 'index',
          title: '序号',
          width: 65,
          align: 'center'
        },
        {
          title: '发布日期',
          key: 'createtime',
          tooltip: true
        },
        {
          title: '班次类型',
          key: 'event'
        },
        {
          title: '换班方式',
          key: 'changeType',
          tooltip: true
        },
        {
          title: '换班请求日期',
          key: 'changeDate',
          minWidth: 20
        },
        {
          title: '换班意向',
          key: 'intention'
        },
        {
          title: '换班对象业务小组',
          key: 'targetTeamName',
          minWidth: 20
        },
        {
          title: '换班对象',
          key: 'targetUserName'
        },
        {
          title: '对象工号',
          key: 'targetUserCode',
          tooltip: true
        },
        {
          title: '对象班次',
          key: 'targetEvent'
        },
        {
          title: '状态',
          align: 'center',
          width: 120,
          render: (h, params) => {
            const row = params.row
            return h(
              'Button',
              {
                props: {
                  type: 'primary',
                  ghost: true,
                  size: 'small'
                },
                on: {
                  click: () => {
                    const relatedId = row.uuid
                    const shiftObjectId = row.shiftObjectId
                    this.timelineState = row.status
                    this.timelineStateDesc = row.chinaStatus
                    this.showTimelineList(relatedId, 1, shiftObjectId)
                  }
                }
              },
              row.chinaStatus
            )
          }
        },
        {
          title: '操作',
          key: 'action',
          width: 130,
          render: (h, params) => {
            const uuid = params.row.uuid
            const shiftObjectId = params.row.shiftObjectId
            // 换班方式（1:指定，2:非指定）
            const changeType = params.row.changeTypeValue
            // 审批状态(见src/config/dict.js > SHIFT_MSG_STATE)
            const status = params.row.status
            // 非指定有意向时有值
            const intention = params.row.intention
            // 换班请求列表是否允许撤销 0可以撤销 非0不允许撤销
            const isCancel = params.row.isCancel
            return h('div', [
              h(
                'Poptip',
                {
                  directives: [
                    {
                      name: 'show',
                      value:
                        changeType === SHIFT_WAY.NON_DESINATION &&
                        status === 3 &&
                        !intention
                    }
                  ],
                  props: {
                    confirm: true,
                    transfer: true,
                    title: '确定与他换班吗？'
                  },
                  on: {
                    'on-ok': () => {
                      this.responseBoardConfirm(
                        uuid,
                        shiftObjectId,
                        SHIFT_MSG_TYPE.SEND,
                        1
                      )
                    }
                  }
                },
                [
                  h(
                    'Button',
                    {
                      props: {
                        type: 'success',
                        size: 'small'
                      }
                    },
                    '确认'
                  )
                ]
              ),
              h(
                'Poptip',
                {
                  directives: [
                    {
                      name: 'show',
                      value:
                        changeType === SHIFT_WAY.NON_DESINATION &&
                        status === 3 &&
                        !intention
                    }
                  ],
                  props: {
                    confirm: true,
                    transfer: true,
                    title: '确定拒绝该换班吗？'
                  },
                  on: {
                    'on-ok': () => {
                      this.responseBoardConfirm(
                        uuid,
                        shiftObjectId,
                        SHIFT_MSG_TYPE.SEND,
                        2
                      )
                    }
                  }
                },
                [
                  h(
                    'Button',
                    {
                      style: {
                        'margin-left': '4px'
                      },
                      props: {
                        type: 'error',
                        size: 'small'
                      }
                    },
                    '拒绝'
                  )
                ]
              ),
              h(
                'Poptip',
                {
                  directives: [
                    {
                      name: 'show',
                      value: [1, 4].indexOf(status) > -1 && isCancel === 0
                    }
                  ],
                  props: {
                    confirm: true,
                    transfer: true,
                    title: '确定撤销换班吗？'
                  },
                  on: {
                    'on-ok': () => {
                      this.responseBoardConfirm(
                        uuid,
                        shiftObjectId,
                        SHIFT_MSG_TYPE.SEND,
                        3
                      )
                    }
                  }
                },
                [
                  h(
                    'Button',
                    {
                      props: {
                        type: 'warning',
                        size: 'small'
                      }
                    },
                    '撤销'
                  )
                ]
              )
            ])
          }
        }
      ],
      dataSend: []
    }
  },
  created () {
    this.columns = this.columnsAnnounce
    this.dataList = this.dataAnnounce
    // this.columns = this.columnsReq
    // this.dataList = this.dataReq
    // this.columns = this.columnsSend
    // this.dataList = this.dataSend
  },
  methods: {
    msgTypeChange (val) {
      switch (val) {
        case 1:
          this.columns = this.columnsAnnounce
          this.dataList = this.dataAnnounce
          break
        case 2:
          this.columns = this.columnsReq
          this.dataList = this.dataReq
          break
        case 3:
          this.columns = this.columnsSend
          this.dataList = this.dataSend
          break
        default:
          this.columns = this.columnsAnnounce
          this.dataList = this.dataAnnounce
          break
      }
      this.doInitSearch()
    },
    respShift () {
      // TODO: resp shift
      console.log('resp shift')
      this.respLoading = true
    },
    doSearch () {
      this.searchLoading = true
      this.$nextTick(() => {
        const sf = cloneDeep(this.searchForm)
        sf.startTime = null
        sf.endTime = null
        TradeProposalAPI.getBulletinList({ ...sf })
          .then(({ data }) => {
            this.searchLoading = false
            if (data.status === 'success') {
              this.dataList = data.data.pageInfo.list
              this.total = data.data.pageInfo.total
              this.remainNums = data.data.remainNums
            }
          })
          .catch(err => {
            console.error('err:', err)
            this.searchLoading = false
          })
      })
    },
    /**
     * @param uuid 换班消息主键
     * @param shiftObjectId 换班对象的id
     * @param eventType 信息类型（1:公告栏 2:被请求 3:我发出）
     * @param operateType 操作类型（1:确认/同意 2:拒绝 3:撤销）
     */
    responseBoardConfirm (uuid, shiftObjectId, eventType, operateType) {
      this.$Message.loading({
        content: '正在提交...',
        duration: 0
      })
      TradeProposalAPI.responseBoardConfirm({
        uuid,
        shiftObjectId,
        eventType,
        operateType
      })
        .then(({ data }) => {
          if (data.code === 200) {
            this.$Message.destroy()
            this.$Message.success('操作成功')
            this.doSearch()
          }
        })
        .catch(err => {
          console.error('err', err)
        })
    }
  }
}
</script>

<style lang="less" scoped>
</style>
