<template>
  <div class="span">
    <validator name='v' style="overflow-y: auto">
      <form novalidate class="form-horizontal select-overspread" @valid="confirmEditcheck = true"
            @invalid="confirmEditcheck = false">
        <div class="row auto">
          <div class="col-sm-6 form-group">
            <label class="font_normal_body">&nbsp;&nbsp;&nbsp;客户姓名</label>
            <input type="text" v-model="row.f_meternumber" class="input_search" style="width:60%" placeholder="表号" :readonly="true">
          </div>
          <div class="col-sm-6 form-group">
            <label class="font_normal_body">&nbsp;&nbsp;&nbsp;客户类型</label>
            <input type="text" v-model="row.f_user_type" class="input_search" style="width:60%" placeholder="客户类型" :readonly="true">
          </div>
          <div class="col-sm-6 form-group">
            <label class="font_normal_body">&nbsp;&nbsp;&nbsp;客户电话</label>
            <input type="text" v-model="row.f_user_phone" class="input_search" style="width:60%" placeholder="客户电话" :readonly="true">
          </div>
          <div class="col-sm-12 form-group">
            <label class="font_normal_body">&nbsp;&nbsp;&nbsp;客户地址</label>
            <input type="text" v-model="row.f_address" class="input_search" style="width:80%" placeholder="客户地址" :readonly="true">
          </div>
          <div class="col-sm-6 form-group" :class="[$v.errortype.required ? 'has-error' : '']">
            <label class="font_normal_body">&nbsp;&nbsp;&nbsp;异常类型</label>
            <input type="text" v-show="false" v-model="$refs.errortype.selectedItems" v-validate:errortype='{required: true }'>
            <v-select style="width:60%"
                      placeholder='异常类型'
                      :value.sync="model.f_error_type"
                      v-model="model.f_error_type"
                      :multiple="true"
                      :options='errorTypes'
                      v-ref:errortype>
            </v-select>
          </div>
          <div class="col-sm-6 form-group" >
            <label class="font_normal_body">&nbsp;&nbsp;&nbsp;派单类型</label>
            <v-select :value.sync="model.f_handlingtype"
                      v-model="model.f_handlingtype"
                      :value-single="true"
                      :options='handling'
                      placeholder='请选择派单类型'
                      close-on-select
                      style="width: 60%">
            </v-select>
          </div>
          <div class="col-sm-6 form-group" v-if="model.f_handlingtype == '转站点'">
            <label class=" font_normal_body" for="f_reciever">&nbsp;&nbsp;&nbsp;选择站点</label>
            <right-tree islist
                        :userid="userid"
                        :source="source"
                        v-on:re-res="reres"
                        :textContent="选择站点管理员"
                        v-ref:f_reciever>
            </right-tree>
          </div>
          <div class="col-sm-6 form-group " v-if="model.f_handlingtype == '转维修员'">
            <label class="font_normal_body">&nbsp;&nbsp;&nbsp;维&ensp;修&ensp;员</label>
            <v-select :value.sync="model.f_reciever"
                      v-model="model.f_reciever"
                      :value-single="true"
                      :options='repairers'
                      placeholder='请选择维修员'
                      close-on-select
                      v-on:change="repiarmancg"
                      style="width: 60%">
            </v-select>
          </div>
        </div>
        <div class="row" style="margin-top: 15px">
          <div class="col-sm-12 form-group ">
            <label class="font_normal_body" >&nbsp;&nbsp;&nbsp;异常描述</label>
            <textarea  style="width: 80%" name="name" rows="3" class="ver-textarea" class="form-control" v-model='model.f_error_msg'></textarea>
          </div>
        </div>
        <div class="row" style="margin-top: 30px">
          <div class="col-sm-12 form-group ">
            <label class="font_normal_body" >&nbsp;&nbsp;&nbsp;备&emsp;&emsp;注</label>
            <textarea  style="width: 80%" name="name" rows="3" class="ver-textarea" class="form-control" v-model='model.f_remarks'></textarea>
          </div>
        </div>
        <div class="row" style="margin-top: 20px">
          <div class="col-sm-12" style="text-align:right;height:auto;margin-top:6px;">
            <button class="button_search" type="button" @click="confirm()" :disabled="!confirmEditcheck">确认</button>
            <button class="button_clear" type="button" @click="close()">取消</button>
          </div>
        </div>
      </form>
    </validator>
  </div>
</template>

<script>
import {HttpResetClass} from 'vue-client'

let readyGen = async function (self) {
  await self.$LoadParams.loadParam()
  self.initQueryParam()
  self.getEmp()
  self.getCurrentUserException()
}
export default {
  title: '物联网异常处理',
  props: ['row', 'errorTypes'],
  data () {
    return {
      row: {},
      repairers: [],
      model: {
        f_error_type: [],
        f_error_msg: [],
        f_handlingtype: '转站点',
        f_reciever: '',
        f_outlets: '',
        f_meetunit: '',
        f_remarks: ''
      },
      handling: [{label: '转站点', value: '转站点'}, {label: '转维修员', value: '转维修员'}],
      confirmEditcheck: false,
      userid: this.$login.f.id,
      source: 'dep=this.getParentByType($organization$).getSpecialResByType($department$),' + 'tool.getFullTree(dep.where(row.hasSpecialRole($派单员$)))'
    }
  },
  ready () {
    readyGen(this)
  },
  watch: {},
  methods: {
    async getCurrentUserException () {
      // 获取当前用户所有的异常
      let http = new HttpResetClass()
      let seenTypes = new Set()
      let seenMsg = new Set()
      let result = await http.load('POST', 'rs/sql/singleTable_OrderBy', {data: {
        items: 'id,f_error_type,f_error_msg',
        tablename: 't_exception',
        condition: `f_userfiles_id = '${this.row.f_userfiles_id}'`,
        orderitem: 'id desc'
      }}, {resolveMsg: null, rejectMsg: null})
      result.data.forEach(row => {
        if (!seenTypes.has(row.f_error_type)) {
          seenTypes.add(row.f_error_type)
          this.model.f_error_type.push(row.f_error_type)
        }
        if (!seenMsg.has(row.f_error_msg)) {
          seenMsg.add(row.f_error_msg)
          this.model.f_error_msg += row.f_error_msg + ','
        }
      })
    },
    confirm () {
      if (!this.row.f_address) {
        return this.$showAlert('地址不能为空，请维护档案信息', 'warning', 2000)
      }
      if (this.model.f_handlingtype == '转维修员') {
        if (!this.model.f_reciever) {
          return this.$showAlert('请选择维修人员', 'warning', 2000)
        }
      } else {
        if (!this.model.f_meetunit) {
          return this.$showAlert('请选择站点', 'warning', 2000)
        }
      }
      let data = {
        f_userinfo_code: this.row.f_userinfo_code,
        f_userinfo_id: this.row.f_userinfo_id,
        f_user_name: this.row.f_user_name,
        f_address: this.row.f_address,
        model: {
          f_user_type: this.row.f_user_type
        },
        f_meternumber: this.row.f_meternumber,
        f_residential_area: '',
        f_contact_phone: this.row.f_user_phone,
        failure: '',
        f_source: '物联网表异常',
        f_handlingtype: this.model.f_handlingtype,
        toRepair: '一级派单',
        f_meetunit: this.model.f_meetunit,
        f_remarks: this.model.f_remarks,
        f_error_msg: this.model.f_error_msg,
        f_error_type: this.model.f_error_type,
        f_reciever: this.model.f_reciever,
        f_operator: this.$login.f.name,
        f_operatorid: this.$login.f.id,
        f_orgid: this.$login.f.orgid,
        f_outlets: this.model.f_outlets,
        f_orgname: this.$login.f.orgs,
        f_repairtype: '整改',
        name: this.$login.f.name,
        ename: this.$login.f.ename
      }
      console.log('data', data)
      this.$resetpost('rs/logic/CreateWorkOrderOutside', {data: data}, {resolveMsg: '下发工单成功', rejectMsg: '下发工单失败'}).then((res) => {
        if (res.data.f_service_id) {
          let http = new HttpResetClass()
          let sql = `update t_exception set f_service_id = '${res.data.f_service_id}'
            where f_error_type in (${this.appendCondition(this.model.f_error_type)}) and f_userfiles_id = '${this.row.f_userfiles_id}'`
          http.load('POST', 'rs/logic/runSQL', { sql: sql }, {resolveMsg: null, rejectMsg: null})
          this.close()
        }
      })
    },
    appendCondition (data) {
      let stringValue = ''
      for (let i = 0; i < data.length; i++) {
        if (data[i]) {
          if (i === data.length - 1) {
            stringValue = stringValue + "'" + data[i] + "'"
          } else {
            stringValue = stringValue + "'" + data[i] + "',"
          }
        }
      }
      return stringValue
    },
    // 当维修员发生改变，获取维修员手机号
    repiarmancg (val) {
      if (val) {
        if (typeof val == 'string') {
          this.model.f_reciever = val
          let http1 = new HttpResetClass()
          http1.load('POST', 'rs/sql/singleTable_OrderBy', {data: {
            items: 'f_user_telephone',
            tablename: 't_user',
            condition: `name  = '${val}'`,
            orderitem: 'id'
          }}, {resolveMsg: null, rejectMsg: null}).then((res) => {
            this.model.f_repairman_phone = res.data[0].f_user_telephone
          })
        }
      }
    },
    // 获取维修员
    getEmp () {
      // let val = {source: 'tool.getChildrenOfResName($维修员$)', userid: `${this.$login.f.id}`}
      let val = {
        source: `this.getParentByType($organization$).getChildByName($维修员$).getUsers()`,
        userid: `${this.$login.f.id}`
      }
      let http = new HttpResetClass()
      http.load('POST', '/rs/search', {data: val}, {resolveMsg: null, rejectMsg: null}).then((res) => {
        res.data.forEach((item) => {
          this.repairers.push({label: `${item.name}`, value: item.name})
        })
      })
    },
    reres (val) {
      if (val.res == undefined || val.res[0] == undefined || val.res[0] == '') {
        return
      }
      console.log('val----------------', val)
      if (val.res.length == 1) {
        this.model.f_meetunit = val.res[0]
        this.model.f_meetunit = val.res[0]
        this.model.f_outlets = val.res[0]
      }
      if (val.resids.length == 1) {
        this.model.f_reciever = val.resids[0]
      }
    },
    initQueryParam () {
      let arr = []
      this.$GetSaleParam.getGasbrand().forEach((item) => {
        let temp = {}
        temp.label = item.label
        temp.value = item.value.f_meter_brand
        arr.push(temp)
      })
      console.log(arr)
      this.meterbrand = [{label: '全部', value: ''}, ...arr]
    },
    close () {
      this.$dispatch('close')
    }
  },
  computed: {}
}
</script>
