<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>
            </tr>
          </template>
          <template partial='body'>
            <td style="text-align: center">
              <nobr>{{row.f_device_type}}</nobr>
            </td>
            <td style="text-align: center">
              <nobr>{{row.f_item_name}}</nobr>
            </td>
            <td style="text-align: center">
              <nobr>{{row.f_item_value}}</nobr>
            </td>
            <td style="text-align: center">
              <nobr v-if="(row.f_item_name).indexOf('异常差值')===-1">{{row.f_repaire_type}}</nobr>
              <nobr v-else>隐患差值不需要转维修</nobr>
            </td>
            <td style="text-align: center">
              <!--<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"  :src1="'/rs/image/file/'+row.f_second_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 class="button_spacing button_search-1" @click="$parent.$parent.$parent.openDefectImg(row)" v-if="!row.f_item_name.includes('差值')">隐患图片</button>
              <button class="button_spacing button_search-1" @click="$parent.$parent.$parent.openRepairImg(row)" v-if="row.f_repaire_type=='维修已处理'" style="margin-top: 3px">维修图片</button>
              <!--<button v-if="row.f_repaire_type == '隐患未处理'" class="button_spacing button_search-1" @click="$parent.$parent.$parent.solveDefect( row, 'solve')">处理隐患</button>-->

            </td>
          </template>
        </data-grid>
      </criteria-paged>
    </div>

    <!--    <div style="overflow-y: scroll;height: 40%" v-if="needRepair&&(check.f_one_count!=0||check.f_two_count!=0)">
          <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 ">
                  <label class="font_normal_body" style="width: 12%">备&nbsp;&nbsp;&nbsp;&nbsp;注</label>
                  <input class="input_search" style="width: 80%;margin-left: 3%" 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-6" 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-6" style="margin-bottom: 10px">
          <label class="font_normal_body">处理后图片</label>
          <img-self :width="200" :height="200" :src="solveModal.preData.repairedImg"></img-self>
        </div>
        <div class="col-sm-6" style="margin-bottom: 10px">
          <label class="font_normal_body">情况说明</label>
          <textarea v-model="solveModal.uploadData.f_item_remakes"></textarea>
        </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="showDefectModal" v-ref:defectModal backdrop="false">
      <header slot="modal-header" class="modal-header">
        隐患照片
      </header>
      <article slot="modal-body" class="modal-body">
        <div class="from-group">
          <div class="row">
            <div class="col-md-6">
              <img-self-safe v-if="defectImg[0]" :src="defectImg[0].url" width="400" height="500"></img-self-safe>
            </div>
            <div class="col-md-6" v-if="defectImg[1]">
              <img-self-safe v-if="defectImg[1]" :src="defectImg[1].url" width="400" height="500"></img-self-safe>
            </div>
          </div>
        </div>
      </article>
      <footer slot="modal-footer" class="modal-footer">
        <button type="button" class="btn btn-default" @click='clone_p'>关闭</button>
      </footer>
    </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
    console.log('uploadData => ' + JSON.stringify(uploadData))
    self.$resetpost('/api/af-safecheck/logic/pcRepairDefect', self.solveModal.uploadData, {resolveMsg: null, rejectMsg: null})
      .then(res => {
        if (res.data.code == 200) {
          self.$showMessage('隐患已处理。')
          self.showSolveModal = false
          self.model.search('1=1', {})
        }
      })
  }

  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.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('/api/af-safecheck/sql/GetUserForRepaireTS', {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 => {
      console.log("66666")
      // console.log(row.f_defect_level.indexOf('一级')!=-1)
      // console.log(row.f_defect_level.indexOf('二级')!=-1)
      // console.log(row.f_defect_level)
      // console.log(row.f_defect_level.indexOf('一级'))
      // console.log(row.f_defect_level.indexOf('二级'))
      if (row.f_defect_level){
        if (row.f_repaire_type == '隐患未处理'&&(row.f_defect_level.indexOf('一级')!=-1||row.f_defect_level.indexOf('二级')!=-1)) {
          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 == '隐患未处理'&&row.f_defect_level && (row.f_defect_level.indexOf('一级')!=-1||row.f_defect_level.indexOf('二级')!=-1))
    console.log('row => ' + JSON.stringify(rows))
    // 开始拼接
    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_project: `${row.f_item_name}:${row.f_item_value}`,
            type: 'selector',
            f_defect_id:row.id,
            options: safecheckOptions
          }]
        }
        repairitems.data.push(newItem)
      } else {
        // 存在则追加
        repairitems.data[existIndex].details.push({
          f_project: `${row.f_item_name}:${row.f_item_value}`,
          f_defect_id:row.id,
          type: 'selector',
          options: safecheckOptions
        })
      }
    })
    uploadData.model.f_repairitems = repairitems
    console.log('uploadData ---> ' + JSON.stringify(uploadData))
    // 调工单接口
    let result = yield self.$resetpost('/api/af-safecheck/logic/callerSend', uploadData)
    console.log('result ===> ' + JSON.stringify(result))
    if (result.data.f_service_id) {
      let updateRes = yield self.$resetpost('/api/af-safecheck/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('api/af-safecheck/sql/GetDefectByPaperIdTS', 100, {
          f_paper_id: 'this.f_paper_id'
        }),
        showSolveModal: false,
        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: ''
          }
        },
        defectImg:[],
        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) {
        console.log("7777777777777777")
        console.log(JSON.stringify(this.check))
        this.model.f_paper_id = this.check.id
        this.model.search(`f_repaire_type != '无隐患'`, {})
      }
      this.getEmp()
    },
    methods: {
      openDefectImg(row){
        console.log(row)
        this.defectImg= [{url: row.f_path}]
        if (row.f_second_path){
          this.defectImg.push({url: row.f_second_path})
        }
        console.log(this.defectImg)
        this.showDefectModal = true
      },
      openRepairImg(row){
        new HttpResetClass().load('post','/api/af-safecheck/sql/getRpaorImg',{data:{defectid:row.id}}, {resolveMsg: null, rejectMsg: null}).then((res)=>{
          console.log(row)
          this.defectImg= [{url: res.data[0].f_first_imgname}]
          if (res.data[0].f_second_imgname){
            this.defectImg.push({url: res.data[0].f_second_imgname})
          }
          console.log(this.defectImg)
          this.showDefectModal = true
        })
      },
      clone_p () {
        // 关闭组件
        this.showDefectModal = false
        this.defectImg = []
      },
      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
        this.showDefectModal = false
      },
      toRepair() {
        this.showToRepairModal = !this.showToRepairModal
      },
      getSiteRes(obj) {
        console.log('siteRes ---> ')
        console.log(obj)
        if(obj.resids[0]){
          this.toRepairModal.preData.f_meetunit = obj.res.join('.')
          this.toRepairModal.preData.f_reciever = obj.resids.join('.')
          this.toRepairModal.preData.f_outlets = obj.res[obj.res.length - 1]
        }else {
          this.toRepairModal.preData.f_meetunit = ''
          this.toRepairModal.preData.f_reciever = ''
          this.toRepairModal.preData.f_outlets = ''
        }
      },
      // 获取维修员
      getEmp() {
        let val = {source: 'this.getParentByType($department$).getAllChildrens().where(row.getAttributes().get($rolestr$).indexOf($维修员$) != -1 ))', 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', 'api/af-safecheck/sql/safe_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) {
          for (let i = 0; i < this.model.rows.length; i++) {
            if (this.model.rows[i].f_defect_level) {
              if (this.model.rows[i].f_repaire_type === '隐患未处理' && (this.model.rows[i].f_defect_level.indexOf('一级') != -1 || this.model.rows[i].f_defect_level.indexOf('二级') != -1)) {
                this.needRepair = true
                return
              }
            }
          }
        }
        this.needRepair = false
      }
    }
  }
</script>
<style lang="less" scoped>
  .select-error {
    button {
      border-bottom: 1px solid #a94442 !important;
    }
  }
</style>
