<!-- 投诉留言 -->
<template>
  <div>
    <Row>
      <DatePicker
        :clearable="false"
        :editable="false"
        placeholder="请选择月份"
        style="width: 200px"
        type="month"
        v-model="searchDateRange"
      ></DatePicker>
      <Button
        :loading="searchLoading"
        @click="doInitSearch"
        style="margin-left: 8px;"
        type="primary"
      >查询</Button>
      <Button
        :disabled="searchLoading"
        @click="showModal = true"
        ghost
        icon="md-add"
        style="margin-left: 8px;"
        type="primary"
        v-permission:add
      >新建</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"
      @on-visible-change="onVisibleChange"
      title="新建投诉留言"
      v-model="showModal"
      width="400"
    >
      <Form
        :label-width="100"
        :model="validateForm"
        :rules="ruleValidate"
        class="complaint-msg-form"
        ref="formValidate"
      >
        <FormItem label="投诉留言类型" prop="leaveType">
          <Select style="width: 200px;" v-model="validateForm.leaveType">
            <Option :key="item.key" :value="item.key" v-for="item in complaintType">{{item.name}}</Option>
          </Select>
        </FormItem>
        <FormItem label="投诉留言对象" prop="leaveUuid">
          <Select
            :loading="searchTagetLoading"
            :maxlength="20"
            :remote-method="handleSearchComplaintTarget"
            @on-change="onUuidChange"
            clearable
            filterable
            placeholder="请输入姓名、员工编号搜索"
            ref="uuid"
            remote
            style="width: 200px;"
            v-model="validateForm.leaveUuid"
          >
            <Option
              :key="item.uuid"
              :value="item.uuid"
              v-for="item in complaintTargets"
            >{{item.name}}</Option>
          </Select>
        </FormItem>
        <FormItem label="备注" prop="remark">
          <Input
            :autosize="{minRows: 4,maxRows: 6}"
            :maxlength="200"
            placeholder="请输入备注"
            type="textarea"
            v-model="validateForm.remark"
          ></Input>
        </FormItem>
        <FormItem label="联系方式" prop="contact">
          <Input
            :maxlength="20"
            placeholder="请输入联系方式"
            style="width: 200px;"
            v-model="validateForm.contact"
          ></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="resetForm">重置</Button>
        <Button :loading="confirmLoading" @click="confirmComplaint" type="primary">提交</Button>
      </div>
    </Modal>
    <Modal :mask-closable="false" :title="`投诉留言状态 - ${timelineStateDesc}`" v-model="showTimeline">
      <Timeline>
        <custom-timeline-item
          :date="formatDate(item.approvalTime)"
          :key="index"
          :passed="index !== timelineList.length - 1 || timelineState !== 1"
          :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 commonList from '@/mixin/commonList'
import { COMPLAINT_TYPE } from '@conf/dict'
import timeline from '@/mixin/timeline'
import ComplaintAPI from '@api/common/complaint'
import cloneDeep from 'lodash/cloneDeep'
import { differenceInDays } from 'date-fns'
export default {
  name: 'complaint-msg',
  mixins: [commonList, timeline],
  data () {
    return {
      columns: [
        {
          type: 'index',
          title: '序号',
          width: 65,
          align: 'center'
        },
        {
          title: '发起日期',
          width: 150,
          key: 'createTime',
          tooltip: true
        },
        {
          title: '发起人',
          render (h, params) {
            return h('div', params.row.map ? params.row.map.userName : '')
          }
        },
        {
          title: '员工编号',
          render (h, params) {
            return h('div', params.row.map ? params.row.map.userCode : '')
          }
        },
        {
          title: '联系方式',
          key: 'contact'
        },
        {
          title: '投诉留言对象',
          render (h, params) {
            return h('div', params.row.map ? params.row.map.targetName : '')
          }
        },
        {
          title: '投诉留言类型',
          render (h, params) {
            return h('div', params.row.map ? params.row.map.leaveType : '')
          }
        },
        {
          title: '备注',
          key: 'remark',
          tooltip: true
        },
        {
          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
                    this.timelineState = row.status
                    this.timelineStateDesc = row.map ? row.map.status : ''
                    this.showTimelineList(relatedId, 4)
                  }
                }
              },
              row.map ? row.map.status : ''
            )
          }
        }
      ],
      dataList: [],
      // form
      showModal: false,
      confirmLoading: false,
      validateForm: {
        leaveType: null,
        leaveUuid: undefined,
        remark: '',
        contact: ''
      },
      complaintTargets: [],
      searchTagetLoading: false,
      ruleValidate: {
        leaveType: {
          required: true,
          type: 'number',
          message: '请选择',
          trigger: 'blur'
        },
        leaveUuid: [
          {
            type: 'number',
            required: true,
            message: '请选择',
            trigger: 'change'
          }
        ],
        remark: [
          {
            required: true,
            message: '不能为空',
            trigger: 'change'
          }
        ],
        contact: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value && value.length === 0) {
                callback(new Error('不能为空'))
              } else {
                var isCorrect = true
                for (let i in value) {
                  if (value[i] < '0' || value[i] > '9') {
                    isCorrect = false
                    break
                  }
                }
                if (isCorrect) {
                  callback()
                } else {
                  callback(new Error('请输入正确的数字'))
                }
              }
            },
            message: '请输入正确的数字',
            trigger: 'change'
          }
        ]
      }
    }
  },
  computed: {
    complaintType () {
      if (this.$store.state.user.isIteamLeader === 1) {
        return COMPLAINT_TYPE
      } else {
        return COMPLAINT_TYPE.slice(1) // 非组长不可选“排班合理性”一项
      }
    }
  },
  methods: {
    doSearch () {
      this.searchLoading = true
      this.$nextTick(() => {
        const dateRange = differenceInDays(
          new Date(this.searchForm.endTime),
          new Date(this.searchForm.startTime)
        )
        if (dateRange > this.$config.DATE_RANGE_QUARTER) {
          this.$Message.warning(
            `日期范围不能超过${this.$config.DATE_RANGE_QUARTER}天`
          )
        } else {
          ComplaintAPI.viewList({ ...this.searchForm })
            .then(({ data }) => {
              this.searchLoading = false
              if (data.status === 'success') {
                this.dataList = data.data.list.map(item => {
                  item.createTime = item.map.createTime
                  return item
                })
                this.total = data.data.total
              }
            })
            .catch(err => {
              console.error('err:', err)
              this.searchLoading = false
            })
        }
      })
    },
    onUuidChange () {
      this.$nextTick(() => {
        this.$refs.uuid.$el.children[0].children[1].children[1].blur()
      })
    },
    onVisibleChange () {
      this.resetForm()
    },
    confirmComplaint () {
      this.$refs['formValidate'].validate(valid => {
        if (valid) {
          this.confirmLoading = true
          const formData = cloneDeep(this.validateForm)
          console.log('formData', formData)
          ComplaintAPI.create({ ...formData })
            .then(({ data }) => {
              this.confirmLoading = false
              if (data.status === 'success') {
                this.showModal = false
                this.$refs['formValidate'].resetFields()
                this.$Message.success('提交投诉留言成功')
                this.doInitSearch()
              }
            })
            .catch(err => {
              console.error('err', err)
              this.confirmLoading = false
            })
        }
      })
    },
    resetForm () {
      this.$refs['formValidate'].resetFields()
    },
    handleSearchComplaintTarget (value) {
      this.searchTagetLoading = true
      const nameCode = value.trim()
      ComplaintAPI.getUserList({ nameCode })
        .then(({ data }) => {
          this.searchTagetLoading = false
          if (data.code === 200) {
            this.complaintTargets = data.data.filter(
              (item, index) => index < 10
            )
          }
        })
        .catch(err => {
          console.error('err', err)
          this.searchTagetLoading = false
        })
    }
  }
}
</script>

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