<template>
  <div>
    <div :style="{'height':needRepair?'60%':'100%'}">
      <criteria-paged :model="model" :pager="false" v-ref:paged>
        <criteria partial='criteria'>
          <div partial>
            <ul class="nav nav-tabs">
              <li role="presentation" class="active"><a style="	color: #5ac0d9 !important;">隐患明细</a></li>
            </ul>
          </div>
        </criteria>
        <data-grid :model="model" partial='list' class="table_sy">
          <template partial='head'>
            <tr>
              <!--              <th>-->
              <!--                <nobr>隐患设备</nobr>-->
              <!--              </th>-->
              <th>
                <nobr>隐患项</nobr>
              </th>
              <th>
                <nobr>隐患原因</nobr>
              </th>
              <th>
                <nobr>隐患处理方式</nobr>
              </th>
              <th>
                <nobr>操作</nobr>
              </th>
              <th>
                <nobr>备注</nobr>
              </th>
            </tr>
          </template>
          <template partial='body'>
            <!--            <td style="text-align: center">-->
            <!--              <nobr>{{row.f_device_type}}</nobr>-->
            <!--            </td>-->
            <td style="text-align: center;white-space: nowrap">
              <nobr>{{row.f_item_name}}</nobr>
            </td>
            <td style="text-align: center;white-space: nowrap">
              <nobr>{{row.f_item_value}}</nobr>
            </td>
            <td style="text-align: center;white-space: nowrap">
              <nobr>{{row.f_repaire_type}}</nobr>
            </td>
            <td style="text-align: center;white-space: nowrap">
              <img-button style="float: left;margin-left: 12%" v-if="row.f_repaire_type != '无隐患' && row.f_repaire_type != '维修已处理'" :src="'/rs/image/file/'+row.f_path" :value="'隐患图片'"></img-button>
              <button v-if="row.f_repaire_type == '维修已处理'" class="button_new-1 button_spacing" @click="$parent.$parent.$parent.solveDefect( row, 'view')">处理详情</button>
              <button v-if="row.f_repaire_type == '隐患未处理'" class="button_spacing button_search-1" @click="$parent.$parent.$parent.dealDefect(row)">处理</button>
            </td>
            <td style="text-align: center;white-space: nowrap">
              <nobr>{{row.f_remarks}}</nobr>
            </td>
          </template>
        </data-grid>
      </criteria-paged>
    </div>

    <div style="overflow-y: scroll;height: 40%" v-if="needRepair">
      <div class="form-horizontal auto">
        <ul class="nav nav-tabs">
          <li role="presentation" class="active"><a style="	color: #000 !important;font-size: 14px">转维修</a></li>
        </ul>
        <validator name='v' @valid="valid = true" @invalid="valid = false">
          <div class="row">
            <div class="col-sm-4" :class="[$v.dispatchtype.required ? 'select-error' : '']">
              <label for="dispatchtype" class="font_normal_body">派发类型</label>
              <input id="dispatchtype" type="text" v-show="false" v-model="$refs.dispatchtype.selectedItems" v-validate:dispatchtype='{required: true }'>
              <v-select :value.sync="toRepairModal.preData.dispatchType" v-model="toRepairModal.preData.dispatchType"
                        :options='toRepairModal.preData.dispatchTypeOptions' placeholder='派发类型'
                        close-on-select v-ref:dispatchtype>
              </v-select>
            </div>
            <div class="col-sm-4  " v-if="toRepairModal.preData.dispatchType == '派发给站点'">
              <label class="font_normal_body">站&nbsp;&nbsp;点</label>
              <right-tree
                islist
                :userid="$login.f.id"
                :source="'dep=this.getParentByType($organization$).getSpecialResByType($department$),tool.getFullTree(dep.where(row.hasSpecialRole($派单员$)))'"
                @re-res="getSiteRes">
              </right-tree>
            </div>
            <div class="col-sm-4   " v-if="toRepairModal.preData.dispatchType == '派发给维修员'" :class="[$v.f_repairman.required ? 'select-error' : '']">
              <input type="text" v-show="false" v-model="toRepairModal.preData.f_repairman" v-validate:f_repairman='{required: true }'>
              <label class="font_normal_body">维修员</label>
              <v-select
                :value.sync="toRepairModal.preData.f_repairman"
                :value-single="true"
                :options='toRepairModal.preData.repairers'
                placeholder='请选择维修员'
                close-on-select></v-select>
            </div>
            <div class="col-sm-4" :class="[$v.f_repairtype.required ? 'select-error' : '']">
              <input type="text" v-show="false" v-model="toRepairModal.preData.f_repairtype" v-validate:f_repairtype='{required: true }'>
              <label class="font_normal_body">报修类型</label>
              <v-select :value.sync="toRepairModal.preData.f_repairtype" style="width:60%"
                        class="select select_list"
                        :value-single="true"
                        :options='toRepairModal.preData.repairTypeOptions'
                        close-on-select>
              </v-select>
            </div>
          </div>
          <div class="row">
            <div class="col-sm-8 form-group">
              <label class="font_normal_body" >备&emsp;&emsp;注</label>
              <input class="input_search" style="width: 60%" type="text" v-model="toRepairModal.preData.f_remarks" placeholder="备注">
            </div>
            <div class="col-sm-4" style="margin-top: 1%">
              <button class="button_search" :disabled="!valid" @click="confirm">转维修</button>
            </div>
          </div>
        </validator>
      </div>
    </div>
    <modal :show.sync="showSolveModal" v-ref:solveModal>
      <div slot="modal-header" class="modal-header">
        <h4 class="modal-title">
          {{solveModal.preData.type == 'view'?'处理详情':'处理隐患'}}
        </h4>
      </div>
      <div slot="modal-body" class="modal-body">
        <div style="width: 100%;height: 36px;background-color: #f1f8ff;float: left">
          <div style="width: 8px;height: 100%;background-color: #6aa6e2;margin-right: 20px;float: left"></div>
          <div style="width: auto;height:100%;float: left;"><p class="title-font" style="margin-top: 5px">处理前</p></div>
        </div>

        <div class="col-sm-6" style="margin-top: 10px">
          <label class="font_normal_body">安&nbsp;检&nbsp;员</label>
          <input class="input_search" style="width: 60%" type="text" disabled="true" v-model="check.f_checker_name" placeholder="安检员">
        </div>
        <div class="col-sm-6" style="margin-top: 10px">
          <label class="font_normal_body">安检时间</label>
          <input class="input_search" style="width: 60%" type="text" disabled="true" v-model="check.f_offsite_time" placeholder="安检时间">
        </div>
        <div class="col-sm-12" style="margin-bottom: 10px">
          <label class="font_normal_body">隐患图片</label>
          <img-self :width="200" :height="200" :src="solveModal.preData.defectImg"></img-self>
        </div>

        <div style="width: 100%;height: 36px;background-color: #f1f8ff;float: left">
          <div style="width: 8px;height: 100%;background-color: #6aa6e2;margin-right: 20px;float: left"></div>
          <div style="width: auto;height:100%;float: left;"><p class="title-font" style="margin-top: 5px">处理后</p></div>
        </div>
        <div class="col-sm-6" style="margin-top: 10px">
          <label class="font_normal_body">处&nbsp;理&nbsp;人</label>
          <input class="input_search" style="width: 60%" disabled="true" type="text" v-model="solveModal.uploadData.f_repairman" placeholder="处理人">
        </div>
        <div class="col-sm-6" style="margin-top: 10px">
          <label class="font_normal_body">处理时间</label>
          <datepicker
            :disabled="solveModal.preData.type == 'view'"
            placeholder='处理时间' style="width:60%"
            :disabled-days-of-week="[]"
            :format="'yyyy-MM-dd'"
            :show-rest-button="reset"
            :value.sync="solveModal.uploadData.f_repair_date">
          </datepicker>
        </div>
        <div v-if="solveModal.preData.type == 'solve'" class="col-sm-12" style="margin-bottom: 10px">
          <label class="font_normal_body">处理后图片</label>
          <avatar-upload :width="200" :height="200" :img-src.sync="solveModal.uploadData.imgSrc" :filename.sync="solveModal.uploadData.filename" v-ref:imginfo></avatar-upload>
        </div>
        <div v-if="solveModal.preData.type == 'view'" class="col-sm-12" style="margin-bottom: 10px">
          <label class="font_normal_body">处理后图片</label>
          <img-self :width="200" :height="200" :src="solveModal.preData.repairedImg"></img-self>
        </div>
      </div>
      <div slot="modal-footer" class="modal-footer" style="text-align: center">
        <button class="button_search" v-if="solveModal.preData.type == 'solve'" @click="ok">确认</button>
        <button class="button_search" @click="cancel">取消</button>
      </div>
    </modal>
    <modal :show.sync="dealModal" v-ref:dealModal backdrop="false">
      <div slot="modal-header" class="modal-header">
        <h4 class="modal-title">
          隐患处理
        </h4>
      </div>
      <div slot="modal-body" class="">

        <div class="col-sm-12" style="margin-top: 30px;padding-left: 20px">
          <label class="font_normal_body">备注</label>
          <textarea  rows="3" style="width: 80%" v-model="dealRow.f_remarks"></textarea>
        </div>
     </div>
      <div slot="modal-footer" class="modal-footer">
        <button class="button_search"  @click="dealok">确认</button>
        <button class="button_search" @click="dealModal=false">取消</button>
      </div>

    </modal>

  </div>
</template>

<script>
import {PagedList, HttpResetClass} from 'vue-client'
import * as Util from '../../Util'
import co from 'co'

const upSolveDefect = function* (self) {
  let uploadData = self.solveModal.uploadData
  //tag)
  self.$resetpost('/rs/logic/pcRepairDefect', self.solveModal.uploadData, {resolveMsg: null, rejectMsg: null})
    .then(res => {
      if (res.data.code == 200) {
        self.$showMessage('隐患已处理。')
        self.showSolveModal = false
        self.model.search('', {})
      }
    })
}

const sendRepair = function* (self) {
  let preData = self.toRepairModal.preData
  let uploadData = self.toRepairModal.uploadData

  if (preData.dispatchType == '派发给站点') {
    uploadData.model.serviceacitivity[0].f_meetunit = preData.f_meetunit
    uploadData.model.serviceacitivity[0].f_reciever = preData.f_reciever
    uploadData.model.f_meetunit = preData.f_meetunit
    uploadData.model.f_orgstr = preData.f_reciever
    uploadData.model.f_outlets = preData.f_outlets
  } else if (preData.dispatchType == '派发给维修员') {
    uploadData.model.serviceacitivity[0].f_reciever = preData.f_repairman
    // uploadData.model.f_meetunit = self.$login.f.orgpathnames
    // uploadData.model.f_orgstr = self.$login.f.orgpathstr
    // uploadData.model.f_outlets = self.$login.f.f_parentname
    uploadData.model.f_meetunit = self.$login.f.deps
    uploadData.model.f_orgid = self.$login.f.orgid
    uploadData.model.f_filiale = self.$login.f.org
    uploadData.model.f_outlets = self.$login.f.deps
    uploadData.model.f_filiale_id = self.$login.f.orgid
    uploadData.toRepair = '一级派单'
  }
  let res = yield self.$resetpost('/rs/sql/GetUserForRepaire', {data: {f_userinfo_id: self.check.f_userinfo_id}})
  preData.userInfo = res.data[0]
  uploadData.model = Object.assign(uploadData.model, preData.userInfo)
  uploadData.user.f_userinfo_id = preData.userInfo.f_userinfo_id
  uploadData.model.f_repair_date = Util.getNowDate()
  uploadData.model.f_repairtype = preData.f_repairtype
  uploadData.model.f_remarks = preData.f_remarks
  // 拼接failure
  let failure = []
  self.model.rows.forEach(row => {
    if (row.f_repaire_type == '隐患未处理') {
      failure.push({
        f_failure_type: row.f_item_name,
        failurecase: row.f_item_value.split(',')
      })
    }
  })
  uploadData.model.failure = failure
  // 拼接repairitems
  let rows = JSON.parse(JSON.stringify(self.model.rows))
  let repairitems = {
    data: []
  }
  let safecheckOptions = [{"data": "已处理"}, {"data": "未处理"}]
  // 取隐患未处理的
  rows = rows.filter(row => row.f_repaire_type == '隐患未处理')
  //tag)
  // 开始拼接
  rows.forEach(row => {
    let existIndex = -1
    // 判断该设备是否已经存在
    for (let i = 0; i < repairitems.data.length; i++) {
      if (repairitems.data[i].f_type == row.f_device_type) {
        existIndex = i
        break
      }
    }
    if (existIndex == -1) {
      // 不存在则新建
      let newItem = {
        f_type: row.f_device_type,
        details: [{
          f_defect_id:row.id,
          f_project: `${row.f_item_name}:${row.f_item_value}`,
          type: 'selector',
          options: safecheckOptions
        }]
      }
      repairitems.data.push(newItem)
    } else {
      // 存在则追加
      repairitems.data[existIndex].details.push({
        f_defect_id:row.id,
        f_project: `${row.f_item_name}:${row.f_item_value}`,
        type: 'selector',
        options: safecheckOptions
      })
    }
  })
  uploadData.model.f_repairitems = repairitems
  //tag)
  // 调工单接口
  let result = yield self.$resetpost('/rs/logic/callerSend', uploadData)
  //tag)
  if (result.data.f_service_id) {
    let updateRes = yield self.$resetpost('/rs/logic/updateDefectState', {itemsId: self.$login.convertToIn(rows.map(row => row.id))})
    if (updateRes.data.code == 200) {
      self.$showMessage('隐患已转维修。')
      self.model.search(`f_repaire_type != '无隐患'`, {})
    }
  }
}

export default {
  title: '隐患项列表',
  data() {
    return {
      model: new PagedList('rs/sql/GetDefectByPaperId', 100, {
        f_paper_id: 'this.f_paper_id'
      }),
      showSolveModal: false,
      dealModal: false,
      dealRow:{},
      showToRepairModal: false,
      showDefectModal: false,
      valid: false,
      needRepair: true,
      solveModal: {
        preData: {
          type: 'view',
          defectImg: '',
          repairedImg: ''
        },
        uploadData: {
          id: '',
          f_repairman: this.$login.f.name,
          f_repair_date: Util.getNowDate().substr(0, 10),
          f_repair_path: '',
          imgSrc: '',
          filename: ''
        }
      },
      toRepairModal: {
        preData: {
          dispatchTypeOptions: [{label: '派发给站点', value: '派发给站点'}, {label: '派发给维修员', value: '派发给维修员'}],
          repairTypeOptions: this.$appdata.getParam('报修类型'),
          dispatchType: '',
          f_repairman: '',
          f_repairtype: '',
          f_remarks: '',
          f_meetunit: '',
          f_reciever: '',
          f_outlets: '',
          userInfo: {},
          repairers: []
        },
        uploadData: {
          model: {
            serviceacitivity: [{
              f_service_acitivity_type: '派单'
            }],
            f_repairitems: {},
            failure: '',
            f_source: '安检',
            f_service_id: '',
            f_contact_phone: '',
            f_meetunit: '',
            f_phone: '',
            f_user_name: '',
            f_address: '',
            f_repair_date: '',
            f_reciever: '',
            f_remarks: '',
            f_user_type: '',
            f_area: '',
            f_unit_name: '',
            f_street: '',
            f_residential_area: '',
            f_building: '',
            f_unit: '',
            f_floor: '',
            f_room: '',
            aState: '',
            f_repairtype: '',
            f_userinfo_id: '',
            f_userinfo_code: '',
            f_orgstr: '',
            f_outlets: '',
            f_attendant: this.$login.f.name
          },
          loginUser: {
            name: this.$login.f.name,
            ename: this.$login.f.ename
          },
          user: {
            f_userinfo_id: ''
          },
          callObj: null
        }
      }
    }
  },
  props: ['check'],
  ready() {
    if (this.check) {
      this.model.f_paper_id = this.check.id
      this.model.search(`f_repaire_type != '无隐患'`, {})
    }
    this.getEmp()
  },
  methods: {
    dealDefect(row){
      //tag)
      this.dealRow = Object.assign({},row)
      this.dealModal = true
    },
    dealok () {
      // //tag)
      // const sql = `update t_devices_items set f_is_repaired = '已处理',f_remarks='${this.dealRow.f_remarks}' where id ='${this.dealRow.id}'`
      // //tag
      this.$resetpost('/rs/logic/checkdealwith', {data: {remak: this.dealRow.f_remarks,f_paper_id:this.dealRow.f_paper_id,id:this.dealRow.id}}, {resolveMsg: '处理成功', rejectMsg: '处理失败!!!'})
      this.dealModal = false
    },
    solveDefect (row, type) {
      this.solveModal.preData.defectImg = '/rs/image/file/' + row.f_path
      this.solveModal.preData.repairedImg = '/rs/image/file/' + row.f_repair_path
      this.solveModal.uploadData.id = row.id
      this.solveModal.preData.type = type
      if (type == 'view') {
        this.solveModal.preData.f_repair_path = '/rs/image/file/' + row.f_repair_path
        this.solveModal.uploadData.f_repairman = row.f_repairman
        this.solveModal.uploadData.f_repair_date = row.f_repair_date
      } else {
        this.solveModal.uploadData.f_repairman = this.$login.f.name
        this.solveModal.uploadData.f_repair_date = Util.getNowDate().substr(0, 10)
      }
      this.showSolveModal = !this.showSolveModal
    },
    ok() {
      if (!(this.solveModal.uploadData.filename && this.solveModal.uploadData.filename.length > 0)) {
        this.$showMessage('请录入处理后照片')
        return
      }
      co(upSolveDefect(this))
    },
    cancel() {
      this.showSolveModal = false
      this.showToRepairModal = false
    },
    toRepair() {
      this.showToRepairModal = !this.showToRepairModal
    },
    getSiteRes(obj) {
      //tag
      //tag
      if(obj.resids[0]){
        this.toRepairModal.preData.f_meetunit = obj.res.join('.')
        this.toRepairModal.preData.f_reciever = obj.resids.join('.')
      }else {
        this.toRepairModal.preData.f_meetunit = ''
        this.toRepairModal.preData.f_reciever = ''
        this.toRepairModal.preData.f_outlets = ''
      }
    },
    // 获取维修员
    getEmp() {
      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) => {
          let http1 = new HttpResetClass()
          http1.load('POST', 'rs/sql/tel_singleTable_OrderBy', {
            data: {
              items: 'f_user_telephone',
              tablename: 't_user',
              condition: `id  =  ${item.id}`,
              orderitem: 'id'
            }
          }, {resolveMsg: null, rejectMsg: null}).then((ress) => {
            this.toRepairModal.preData.repairers.push({label: `${item.name}：${ress.data[0].f_user_telephone}`, value: item.name})
          })
        })
      })
    },
    confirm() {
      if (this.toRepairModal.preData.dispatchType == '派发给站点' && !this.toRepairModal.preData.f_meetunit) {
        this.$showMessage('请选择站点。')
        return
      }
      co(sendRepair(this))
    }
  },
  watch: {
    'check'() {
      this.model.f_paper_id = this.check.id
      this.model.search(`f_repaire_type != '无隐患'`, {})
    },
    'model.rows'() {
      if (this.model.rows.length > 0) {
        if (this.model.rows[0].f_repaire_type == '隐患未处理') {
          this.needRepair = true
          return
        }
      }
      this.needRepair = false
    }
  }
}
</script>
<style lang="less" scoped>
.select-error {
  button {
    border-bottom: 1px solid #a94442 !important;
  }
}
</style>
