<template>
  <th-dialog
    ref="dialog"
    class="th-supervise"
    v-bind="dialogProps"
    :loading="loading"
    @handleConfirm="handleConfirm"
  >
    <template>
      <th-form
        ref="form"
        class="th-supervise--form"
        v-bind="form"
        :options="{
          supervisionTemplateId: templateOptions,
          superviceObjectIds: superviceOptions,
          sendObjectIds: superviceOptions,
        }"
        @handleSubmit="handleSubmit"
      >
        <!-- 人员联系方式 -->
        <template #pMsg="scope">
          <div class="pMsg">
            <th-textarea-tags v-model="scope.data.pMsg" />
            <th-table
              ref="table"
              v-bind="list"
              @handleSelectionChange="handleSelectionChange"
            />
          </div>
        </template>
      </th-form>
      <person-dialog
        ref="personDialog"
        :request="request"
        :host-org-options="hostOrgOptions"
        @onSelect="onSelectPerson"
      />
    </template>
  </th-dialog>
</template>

<script>
import mixin from './mixin.js'
import baseForm from './../../../src/mixins/baseForm'
import baseTable from './../../../src/mixins/baseTable'
import PersonDialog from './PersonDialog/PersonDialog'

export default {
  name: 'ThSupervise',
  components: {
    PersonDialog
  },
  mixins: [baseForm, baseTable, mixin],
  inject: ['onSearch'],
  data() {
    const style = {
      display: 'inline-block',
      width: '50%'
    }
    return {
      loading: false,
      dialogProps: {
        title: '工单督办',
        width: '80%',
        props: {
          appendToBody: true
        },
        buttons: [
          {
            key: 'submit',
            label: '确认并发送'
          }
        ]
      },
      form: {
        labelWidth: '120px',
        data: {
          supervisionTemplateId: '',
          supervisionAppNo: '',
          supPerson: '',
          objType: '',
          superviceObjectIds: [],
          sendObjectIds: [],
          orgNo: '',
          superviceMsg: '',
          sendMsg: '',
          pMsg: []
        },
        items: [
          {
            label: '督办规则',
            component: 'title',
            props: {
              title: '督办规则',
              type: 'primary'
            }
          },
          {
            label: '督办参考模板',
            prop: 'supervisionTemplateId',
            component: 'select',
            style
          },
          {
            label: '督办工单编号',
            prop: 'supervisionAppNo',
            component: 'input',
            style,
            props: {
              disabled: true,
              maxlength: 200
            }
          },
          {
            label: '督办人员',
            prop: 'supPerson',
            component: 'input-button',
            buttonClick: this.handleShowPerson,
            buttonText: '新',
            style,
            props: {
              disabled: true
            }
          },
          {
            label: '抄送人员',
            prop: 'objType',
            component: 'input-button',
            buttonClick: this.handleShowObjType,
            buttonText: '新',
            style,
            props: {
              disabled: true
            }
          },
          {
            label: '督办对象',
            prop: 'superviceObjectIds',
            component: 'select',
            props: {
              multiple: true
            },
            style,
            class: 'multiple-form-item'
          },
          {
            label: '抄送对象',
            prop: 'sendObjectIds',
            component: 'select',
            props: {
              multiple: true
            },
            style,
            class: 'multiple-form-item'
          },
          {
            label: '督办单位',
            prop: 'orgNo',
            component: 'select',
            style,
            show: this.isShowOrg
          },
          {
            label: '督办内容',
            prop: 'superviceMsg',
            component: 'input',
            props: {
              type: 'textarea',
              autosize: {
                minRows: 4
              }
            }
          },
          {
            label: '抄送内容',
            prop: 'sendMsg',
            component: 'input',
            props: {
              type: 'textarea',
              autosize: {
                minRows: 4
              }
            }
          },
          {
            label: '人员联系方式',
            prop: 'pMsg',
            component: 'slot'
          }
        ],
        buttons: []
      },
      list: {
        columns: [
          {
            prop: 'sendObject',
            label: '督办人员类型'
          },
          {
            prop: 'custName',
            label: '督办人员姓名'
          },
          {
            prop: 'custTel',
            label: '督办人员电话'
          }
        ],
        showIndex: false,
        showSelection: true,
        showPagination: false,
        props: {
          height: '300px',
          rowKey: 'custTel'
        }
      },
      rules: {
        superviceObjectIds: [
          this.$rules.required()
        ]
      },
      subPersonList: [], // 督办人员列表
      sendPersonList: [], // 抄送人员列表
      row: null
    }
  },
  watch: {
    'form.data.supervisionTemplateId': {
      handler(val) {
        this.initDateFrom(val)
      },
      immediate: true
    },
    'list.selectedRows'(rows) {
      let pMsg = []
      if (this.$length(rows)) {
        const name1 = []
        const name2 = []
        const name3 = []
        const name4 = []
        rows.forEach(d => {
          if (d.sendObject === '督办人员') {
            name1.push({ value: d.custName + ' ' + d.custTel })
          } else if (d.sendObject === '抄送人员') {
            name2.push({ value: d.custName + ' ' + d.custTel })
          } else if (d.sendObject === '督办对象') {
            name3.push({ value: d.custName + ' ' + d.custTel })
          } else if (d.sendObject === '抄送对象') {
            name4.push({ value: d.custName + ' ' + d.custTel })
          }
        })
        if (name1.length) {
          pMsg.push({ label: '督办人员:' })
          pMsg = pMsg.concat(name1)
        }
        if (name2.length) {
          pMsg.push({ label: '抄送人员:' })
          pMsg = pMsg.concat(name2)
        }
        if (name3.length) {
          pMsg.push({ label: '督办对象:' })
          pMsg = pMsg.concat(name3)
        }
        if (name4.length) {
          pMsg.push({ label: '抄送对象:' })
          pMsg = pMsg.concat(name4)
        }
      }
      this.form.data.pMsg = pMsg
    }
  },
  methods: {
    // 显示弹框
    showDialog(row) {
      if (!row) {
        this.$message.warning('请选择一条数据！')
      } else {
        this.row = row
        this.$refs.dialog.showDialog()
        this.FetchTemplateOptions()
        this.FetchHostOrgOptions()
        this.FetchObjectList()
      }
    },
    // 切换模板初始化表单
    initDateFrom(templateId) {
      this.form.data.sendObjectIds = []
      this.form.data.superviceObjectIds = []
      this.form.data.supervisionAppNo = new Date().getTime()
      this.updateForm(templateId)
      this.fetchDistribute()
    },
    // 获取模板详情，更新表单
    updateForm(templateId) {
      const data = this.templateOptions.find(d => d.value === templateId)
      if (data) {
        this.form.data.supervisionLevel = data.SUPERVICE_LEVEL
        this.form.data.sendObjectIds = data.SEND_OBJECT_IDS.split(',')
        this.form.data.superviceObjectIds = data.SUPERVICE_OBJECT_IDS.split(',')
        this.form.data.supervisionTemplateId = data.ID
        this.form.data.startTime = data.START_TIME
        this.form.data.endTime = data.END_TIME
        this.fetchChangeMsg(data)
        if (this.row && this.row.type !== '10') {
          this.list.data = []
          this.$refs.table.$refs.table.clearSelection()
          this.fetchSupPerson(data)
          this.fetchSendPerson(data)
        }
      }
    },
    // 解析短信的内容
    fetchChangeMsg(data) {
      if (this.request.fetchChangeMsg) {
        const me = this.row
        const params = {
          message: data.SUPERVICE_MSG,
          repeatTime: data.REPEAT_TIME,
          sjdw: data.SJDW,
          appNo: me.appNo,
          sheetId: me.sheetId,
          dispatchTime: me.dispatchTime,
          dispatchPerson: me.dispatchPerson,
          dispatchTeam: me.dispatchTeam || '',
          dispatchID: me.dispatchID || '',
          flag: me.flag,
          ym: me.ym || '',
          type: me.type,
          custNo: me.custNo,
          custName: me.custName,
          tel: me.tel,
          addr: me.faultAddress,
          orgName: me.sysOrgName
        }
        const params2 = Object.assign({}, params, {
          message: data.SEND_MSG
        })
        // 督办短信
        this.request.fetchChangeMsg(params).then(res => {
          if (res.data.code === 0) {
            this.form.data.superviceMsg = res.data.data
          }
        })
        // 抄送短信
        this.request.fetchChangeMsg(params2).then(res => {
          if (res.data.code === 0) {
            this.form.data.sendMsg = res.data.data
          }
        })
      }
    },
    // 查询督办人员的电话和名称
    fetchSupPerson(data) {
      if (this.request.fetchSearchPerson) {
        const params = {
          supervisionType: '1',
          templeteId: data.ID,
          personType: data.SUPERVICE_OBJECT_IDS,
          busiType: this.row.type,
          sheetId: this.row.sheetId,
          flag: false
        }
        this.request.fetchSearchPerson(params).then(res => {
          if (res.data.code === 0) {
            this.subPersonList = res.data.data
            // 督办人员
            this.form.data.supPerson = this.subPersonList.map(d => d.realName).join(',')
            // 督办人员电话
            this.form.data.supPersonTel = this.subPersonList.map(d => d.mobile).join(',')
            // 表格添加数据
            this.subPersonList.forEach(d => {
              if (!this.list.data.find(i => i.custTel === d.mobile)) {
                const item = {
                  sendObject: '督办对象',
                  custName: d.realName,
                  custTel: d.mobile,
                  isRepair: '1'
                }
                this.list.data.push(item)
                this.$nextTick(() => {
                  this.$refs.table.$refs.table.toggleRowSelection(item, true)
                })
              }
            })
          }
        })
      }
    },
    // 查询抄送人员的电话和名称
    fetchSendPerson(data) {
      if (this.request.fetchSearchPerson) {
        const params = {
          templeteId: data.value,
          supervisionType: '2',
          personType: data.SEND_OBJECT_IDS,
          busiType: this.row.type,
          sheetId: this.row.sheetId,
          flag: false
        }
        this.request.fetchSearchPerson(params).then(res => {
          if (res.data.code === 0) {
            this.sendPersonList = res.data.data
            // 抄送人员
            this.form.data.objType = this.sendPersonList.map(d => d.realName).join(',')
            // 抄送人员电话
            this.form.data.objTypeTel = this.sendPersonList.map(d => d.mobile).join(',')
            // 表格添加数据
            this.sendPersonList.forEach(d => {
              if (!this.list.data.find(i => i.custTel === d.mobile)) {
                const item = {
                  sendObject: '抄送人员',
                  custName: d.realName,
                  custTel: d.mobile,
                  isRepair: '1'
                }
                this.list.data.push(item)
                this.$nextTick(() => {
                  this.$refs.table.$refs.table.toggleRowSelection(item, true)
                })
              }
            })
          }
        })
      }
    },
    // 是否显示督办单位字段
    isShowOrg() {
      // Orgflag
      return this.session && this.session.orgLevel === '2' && this.row && this.row.type === '30'
    },
    //非抢市级用户，默认派单人员为督办人员，默认督办单位
    fetchDistribute() {
      if (this.isShowOrg() && this.request.fetchDistribute) {
        const params = {}
        params.params = JSON.stringify({
          filter: this.$util.serialize({
            sheetId: this.row.sheetId
          })
        })
        this.request.fetchDistribute(params).then(res => {
          if (res.data.successful && this.$length(res.data.resultValue.items)) {
            const data = res.data.resultValue.items[0]
            this.form.data.supPerson = data.dispatchPerson || ''
            this.form.data.supPersonTel = data.dispatchPersonTel || ''
            this.form.data.orgNo = data.sysOrgId
            this.form.data.superviceObjectIds = '03'

            const personName = (data.dispatchPerson || '').split(','
            )
            const personTel = (data.dispatchPersonTel || '').split(','
            )
            this.list.data = []
            this.$refs.table.$refs.table.clearSelection()
            const pMsg = [{ label: '督办人员:' }]
            personName.forEach((d, i) => {
              const custTel = personTel.length > i ? personTel[i] : ''
              pMsg.push({ value: d + ' ' + custTel })
              const item = {
                sendObject: '督办对象',
                custName: d,
                custTel
              }
              this.list.data.push(item)
              this.$nextTick(() => {
                this.$refs.table.$refs.table.toggleRowSelection(item, true)
              })
            })
            this.form.data.pMsg = pMsg.length > 1 ? pMsg : []
          }
        })
      }
    },
    // 点击确定
    handleConfirm() {
      this.$refs.form.handleSubmit({ key: 'submit' })
    },
    // 表单提交
    handleSubmit(data, btn) {
      if (this.request.fetchSuperviceSave) {
        data.sendObjectNames = data.sendObjectIds.map(a => {
          return this.superviceOptions.find(b => b.value === a).label
        }).join(',')
        data.superviceObjectNames = data.superviceObjectIds.map(a => {
          return this.superviceOptions.find(b => b.value === a).label
        }).join(',')
        data.sendObjectIds = data.sendObjectIds.join(',')
        data.superviceObjectIds = data.superviceObjectIds.join(',')
        data.pMsg = data.pMsg.map(d => d.label || d.value).join(',')
        delete data.pMsg
        const params = {
          model: {
            ...data,
            supervisionSheetId: this.row.sheetId,
            orgNo: this.row.sysOrgId
          }
        }
        this.loading = true
        this.request.fetchSuperviceSave(params).then(res => {
          this.loading = false
          if (res.data.successful && res.data.resultValue.items[0].code === 0) {
            this.$message.success('督办成功！')
            this.$refs.form.resetFields()
            this.$refs.dialog.handleCancel()
            this.onSearch()
            // TODO: 话务系统督办呼叫功能
            this.sendCallnew()
            // TODO: 是否开启外网话务
          } else {
            this.$message.error('督办失败，请稍后重试或联系管理员！')
          }
        })
      }
    },
    // 话务系统督办呼叫功能
    sendCallnew() {
      // 是否开启话务系统  是否自动外呼功能
      const { ISGREENPHONE, ISAUTODIAL } = this.repairSysParams || {}
      if (ISGREENPHONE === '1' && ISAUTODIAL === '1' && this.form.data.supPersonTel) {

        const { appNo, busiTypeName, handleTime, remainderTime, dispatchTime } = this.row
        var callText = '尊敬的用户您好，感谢您接听供电服务指挥中心来电，本次来电告知您有一张' + busiTypeName + '工单待处理'

        if (handleTime != null && handleTime !== 'undefined') {
          callText += '，受理时间为' + handleTime
        }
        if (remainderTime != null && remainderTime !== 'undefined') {
          callText += '，剩余时长为' + remainderTime
        }
        if (dispatchTime != null && dispatchTime !== 'undefined') {
          callText += '，业务办结时限为' + dispatchTime
        }
        callText += '，请及时处理。'

        // 督办呼叫名单
        const custTels = this.form.data.supPersonTel.split(',')
        custTels.forEach(d => {
          fetch('http://' + window.location.hostname + '/RDConnector/GetOutboundInfo.html', {
            method: 'POST',
            body: JSON.strignify({
              info: [{
                callidout: d,
                Gdbh: appNo,
                Gdlxbh: busiTypeName,
                telephone: d,
                Text: callText,
                Leixing: '1',
                Wblx: '02'
              }]
            }),
            headers: { 'Content-Type': 'application/json;charset=utf-8' }
          }).then(response => response.json()) //定义返回的类型和数据格式
            .then(data => console.log(data)) // 返回的数据
        })
      }
    },
    // 显示督办人员选择框架
    handleShowPerson() {
      this.$refs.personDialog.showDialog('1')
    },
    // 显示抄送人员选择框架
    handleShowObjType() {
      this.$refs.personDialog.showDialog('2')
    },
    // 选择人员
    onSelectPerson(rows, source) {
      if (source === '1') {
        rows.forEach(d => {
          if (this.form.data.supPerson.indexOf(d.realName) < 0) {
            const item = d.realName
            this.form.data.supPerson += this.form.data.supPerson ? ',' + item : item
          }
        })
      } else {
        rows.forEach(d => {
          if (this.form.data.objType.indexOf(d.realName) < 0) {
            const item = d.realName
            this.form.data.objType += this.form.data.objType ? ',' + item : item
          }
        })
      }
      
      this.afterSelectPerson(rows, source)
    },
    // 督办人员新加之后
    afterSelectPerson(rows, source) {
      // 表格添加数据
      rows.forEach(d => {
        if (!this.list.data.find(i => i.custTel === d.mobile)) {
          const item = {
            sendObject: source === '1' ? '督办对象' : '抄送人员',
            custName: d.realName,
            custTel: d.mobile,
            isRepair: '1'
          }
          this.list.data.push(item)
          this.$nextTick(() => {
            this.$refs.table.$refs.table.toggleRowSelection(item, true)
          })
        }
      })
    }
  }
}
</script>

<style lang="scss">
.th-supervise--form{
  .multiple-form-item{
    .el-cascader__tags,.el-select__tags{
      flex-wrap: nowrap;
    }
    .el-cascader,.el-select{
      overflow: hidden;
    }
  }
}
</style>
