<template>
  <form novalidate class="form-horizontal  span auto compatible"
        style="width: 95%;margin: auto;position: relative;top: 40px">
<!--    <div class="row" style="display: flex;justify-content: center;margin-bottom:20px;">
      <div style="width: 95%;">
        <history-info :user="user"></history-info>
      </div>
    </div>-->
    <div class="auto app-text" style="margin: 5px 0;" v-if="$parent.$parent.ic_imgs && $parent.$parent.ic_imgs.length>0">
      <div class="panel" style="padding: 10px 10px 5px 10px;">
        <div class="panel-body panel-self">
          <div class="row col-xs-12 col-sm-12 col-md-12">
            <p class="panel-title col-xs-3 text-left font" style="font-weight: bolder;">工商示意图: </p>
            <p class="panel-title col-xs-9 text-left input-font" style="display: flex;flex-wrap: wrap;">
              <android-img-self v-for="img in $parent.$parent.ic_imgs" :imgid="'ic_imgs'+img.id" :src="Url+'/rs/tencentfile/getTencentFile/'+img.id" style="margin: 3px" :width="140" :height="170">
              </android-img-self>
            </p>
          </div>
        </div>
      </div>

    </div>
    <div v-if="$parent.$parent.f_user_defects && $parent.$parent.f_user_defects.length > 0 ">
      <div style="width: 95%;margin: auto">
        <div class="flex panel panel-default well" style="width: 100%;display: inline-block">
          <div class="panel-body bg-info">
            <!--上次隐患是否处理-->
            <div v-for="(index,defect) in $parent.$parent.f_user_defects" class="row col-xs-12 col-sm-6 col-md-6 app-row">
              <div class="row defect-center-label">
                <div class="col-xs-6 col-sm-6 col-md-6" style="margin-top: 7px">
                  <label class="font text-left">
                    {{ defect.f_defect_type }}:{{ defect.f_defect_name }}:{{ defect.f_defect_value }}
                  </label>
                </div>
                <div class="col-xs-6 col-sm-6 col-md-6" style="margin-top: 7px">
                  <v-select id="f_distinct" :value.sync="defect.f_is_eliminate" class="input-font"
                            :options='isEliminate' placeholder='请选择是否处理' :value-single="true"
                            v-model="defect.f_is_eliminate"
                            close-on-select clear-button></v-select>
                </div>
              </div>
              <div class="row defect-center-value">
                <div class="form-group col-sm-12">
                  <div class="auto">
                    <div class="panel">
                      <div class="row panel panel-default repair-info-content repair-bg" style="height: 160px;overflow: scroll;">
                        <div style="height: auto" v-for="(idex,img) in defect_center_images(defect.f_defect_img_path)">
                          <div class="col-xs-4 col-sm-3 col-md-2" style="margin-bottom: 35px">
                            <img-self :src="img" alt="总体安检照片" :width="140" :height="170"></img-self>
                            <img src="../../assets/删除.png" v-if="role !='androidview'"
                                 @click="delfile(img,idex,index)" style="width: 15px;" alt="">
                          </div>
                        </div>
                      </div>
                      <div class="row col-xs-12 col-sm-12 col-md-6 text-right div-photo">
                        <button type="button" name="button" class="btn btn-photo" v-if="role !='androidview'"
                                @click="takePic(index, defect.f_defect_name)">拍照
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div>
      <div v-for="dev in devices" style="width: 95%;margin: auto">
        <div class="flex panel panel-default well" style="width: 100%;display: inline-block">
          <div class="panel-body bg-info">
            <div class="text-center">
              <label class="control-label" style="font-weight: bold">{{ dev.device }}<span v-if="dev.checkmust">*</span>{{
                  '[' + paper['device' +
                  dev.n].length + ']'
                }}</label>
              <span :class="style__" class="glyphicon glyphicon-plus" @click="addDevice(dev)" style="font-size: x-large"
                    v-if="dev.device!='燃气表' && role != 'androidview'"></span>
            </div>
            <ul class="list-unstyled panel-ul">
              <li
                :id="'vc-list-'+attach+'-'+$index"
                v-for="row in paper['device'+ dev.n]">
                <!--v-bind:class="{ 'bg-success': isSelected(row) }"-->
                <div partial class="panel panel-default well" style="padding: 0px">
                  <div class="panel-body inbg">
                    <div class="row form-group">
                      <div class="row">
                      <span class="li-font" v-for="items in row.f_items"
                            v-if=" items.f_item_value && items.f_item_value != '' ">
                        {{ items.f_item_name }}:{{ items.f_item_value }}
                        <!--<span class="li-font" v-for="item in items.f_item_value">-->
                        <!--{{item}},&nbsp;&nbsp;&nbsp;-->
                        <!--</span>-->
                      </span>
                        <div class="text-right">
                          <img style="width: 25px" src="../../assets/remove.png" :class="style__"
                               @click="removeDevice(dev,row)"
                               v-if="dev.device!='燃气表' && role != 'androidview'"></img>
                          <img style="width: 25px;margin-left: 15px" src="../../assets/edit.png" @click="editDevice(dev,$index)"></img>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <partial name="default"></partial>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <devices-item :show.sync="showDevice" :role="role" :operation="operation" :config="config" :device="dev"
                    :idx="idx"
                    v-if="showDevice"></devices-item>
    </div>
  </form>


</template>

<script>
import Vue from 'vue'
import {HttpResetClass} from 'vue-client'
import co from 'co'
import * as Util from '../Util'
import DevicesItem from './DevicesItemNoncivil'

let getRepairs = async function (self, url) {
  // 获取配置信息
  try {
    let val = {
      source: 'this.getParentByType($department$).getChildByName($维修员$).getUsers()',
      userid: `${Vue.$login.jwt}`
    }
    let repairs = []
    let res = await Vue.resetpost(`${url}/rs/search`, {data: val}, {resolveMsg: null, rejectMsg: null})
    res.data.forEach((item) => {
      repairs.push({label: item.name, value: item})
    })
    self.f_repair_person = repairs
  } catch (error) {
    console.log('error', error)
  }
}

export default {
  components: {DevicesItem},
  title: '安检项界面',
  data () {
    return {
      isBack: false,
      selectrepair: this.$parent.$parent.data.safecheckrepair,
      ifchecked: this.$parent.$parent.data.whetherrepair === 1,
      // showrepair: this.$parent.$parent.data.whetherrepair === 1,
      showrepair: false,
      paper: this.$parent.$parent.data,
      devices: this.$parent.$parent.devices,
      config: this.$parent.$parent.config,
      showDevice: false,
      dev: {},
      operation: '',
      idx: '',
      safeCheckToRepair: '',
      showCheckToRepair: false,
      userid: '',
      // userid: this.$login.f.id,
      source:
        'dep=this.getParentByType($organization$).getSpecialResByType($department$),' +
        'tool.getFullTree(dep.where(row.getChildByName($派单员$) != null))',
      isback: false,
      defectDevice: {},
      deviceCollect: {},
      deviceCollects: [],
      callObj: null,
      user: {card_id: this.$parent.$parent.item.f_card_id, sid: this.$parent.$parent.item.f_card_id},
      role: this.$parent.$parent.role,
      hasDevice: false,
      Url: this.$androidUtil.getProxyUrl(),
      // eliminates: this.eliminates(),
      defectIndex: null,
      result: '正常',
      showEliminates: false,
      picture: [],
      abc: [],
      isEliminate: [
        {label: '请选择', value: ''},
        {label: '已处理', value: '已处理'},
        {label: '未处理', value: '未处理'}
      ]
    }
  },
  methods: {
    defect_center_images (image) {
      console.log("defect_center_images 传来的数据为",image)
      if (!image) {
        return []
      } else {
        console.log(image.split(','))
        return image.split(',')
      }
    },
    delfile(imgpath,idx,index) {
      if (imgpath == Vue.nopic || !imgpath) {
        return
      } else {
        HostApp.delfile(imgpath)
        let conststr = this.$parent.$parent.f_user_defects[index].f_defect_img_path.split(",")
        conststr.splice(idx, 1);
        let result = ''
        for (let i = 0; i < conststr.length; i++) {
          if (i === (conststr.length-1)) {
            result += conststr[i]
          } else {
            result += conststr[i] + ','
          }
        }
        this.$parent.$parent.f_user_defects[index].f_defect_img_path = result
      }
    },
    takePic (prop, title) {
      HostApp.__callback__ = this.cameraCallBack
      HostApp.__this__ = this
      console.log('this.devices.takePic' + prop + 'title:' + title)
      let fileName = Util.guid() + '-' + 'devices' + '' + this.idx + '-' + 'center' + prop + '.jpg'
      HostApp._open_a_page({
        type: 'boomerang',
        page: 'com.aofeng.hybrid.android.peripheral.CameraActivity',
        param: {
          file: fileName,
          requestCode: 111,
          callback: 'javascript:HostApp.__callback__("' + prop + '", "%s");',
          watermark: title + '\t时间：' + Util.toStandardTimeString() + '\t' + Vue.user.name
        }
      })
    },
    cameraCallBack (prop, fileName) {
      console.log("进入devices 拍照回调",prop,fileName)
      if (!HostApp.__this__.$parent.$parent.f_user_defects[prop].f_defect_img_path) {
        HostApp.__this__.$parent.$parent.f_user_defects[prop].f_defect_img_path = ''
      }
      if (HostApp.__this__.$parent.$parent.f_user_defects[prop].f_defect_img_path==='') {
        HostApp.__this__.$parent.$parent.f_user_defects[prop].f_defect_img_path = fileName
      } else {
        HostApp.__this__.$parent.$parent.f_user_defects[prop].f_defect_img_path = HostApp.__this__.$parent.$parent.f_user_defects[prop].f_defect_img_path + "," + fileName
      }
      // HostApp.__this__.$set(this.$parent.$parent.f_user_defects[prop].f_defect_img_path, fileName + '?' + Math.random())
      console.log("打印合并照片数据",this.$parent.$parent.f_user_defects[prop].f_defect_img_path)
      HostApp.__callback__ = null
      HostApp.__this__ = null
    },
    cancel () {
      this.showEliminates = false
    },
    save () {
      this.showEliminates = false
    },
    check (index, val) {
      console.log('index======》' + index)
      console.log('val======》' + JSON.stringify(val))
      this.defectIndex = index
      this.defect = val
      this.showEliminates = true
    },
    changse (val) {
      console.log('是否消除val====>' + val)
      if (val == undefined) {
        return
      }
    },
    eliminates () {
      return [{label: '已消除', value: '已消除'},
        {label: '未消除', value: '未消除'}]
    },
    addDevice (dev) {
      this.operation = 'add'
      this.paper['device' + dev.n].push({})
      this.dev = dev
      console.log('length', this.paper['device' + dev.n])
      this.idx = this.paper['device' + dev.n].length - 1
      this.showDevice = true
      // this.$goto('device-item', {config: this.config, device: dev, idx: this.paper['device' + dev.n].length - 1}, 'paper-router')
    },
    editDevice (dev, idx) {
      this.operation = 'edit'
      console.log('dev' + JSON.stringify(dev))
      console.log('idx' + idx)
      this.dev = dev
      this.idx = idx
      this.showDevice = true
      // this.$goto('device-item', {config: this.config, device: dev, idx: idx}, 'paper-router')
    },
    removeDevice (dev, row) {
      this.$showMessage('确定删除该信息？', ['confirm', 'cancel']).then((res) => {
        console.log('res=====>' + res)
        if (res === 'confirm') {
          this.paper['device' + dev.n].$remove(row)
          // this.$parent.$parent.devicesCollect()
          this.$dispatch('devicesCollect')
        }
      })

    },
    showrepairchange (event) {
      if (event.srcElement.checked) {
        this.showrepair = true
        this.$parent.$parent.data.whetherrepair = 1
      } else {
        this.showrepair = false
        this.$parent.$parent.data.whetherrepair = 0
        this.$parent.$parent.data.safecheckrepair = ''
      }
    },
    changeRepairman (val) {
      if (val.length !== 0) {
        this.$parent.$parent.data.safecheckrepair = val
      }
    },
    readRepair () {
      let url = this.$androidUtil.getProxyUrl()
      let gen = getRepairs(this, url)
      return co(gen)
    },
    repiarmancg (val) {
      if (val) {
        console.log(val)
        this.model.serviceacitivity[0].f_reciever = val.name
        let http1 = new HttpResetClass()
        http1.load('POST', `${this.Url}/rs/sql/tel_singleTable_OrderBy`, {
          data: {
            items: 'f_user_telephone',
            tablename: 't_user',
            condition: `name  = '${val}'`,
            orderitem: 'id'
          }
        }, {resolveMsg: null, rejectMsg: null}).then((ress) => {
          this.model.f_repairman_phone = ress.data[0].f_user_telephone
        })
      }
    }
  },
  ready () {
    console.log('this.paper.f_user_defects======>' + JSON.stringify(this.$parent.$parent.f_user_defects))
    for (let i; i < this.$parent.$parent.f_user_defects.length; i++) {
      this.$parent.$parent.f_user_defects[i].f_is_eliminate = ''
    }
    if (!this.$parent.$parent.showBack) {
      this.$parent.$parent.showBack = true
    }
    // console.log('this.defects===----------->>' + JSON.stringify(this.defects))
    this.$parent.$parent.firstEnter = true
    // this.$parent.$parent.devicesCollect()
    this.$dispatch('devicesCollect')
  },
  events: {
    'finishChoose' (val) {
      console.log('已选择安检设备',val)
      this.$parent.$parent.hasDevice = true
      this.picture = val
      this.$dispatch('devicesCollect')
      // this.$parent.$parent.devicesCollect()
    }
  },
  watch: {
    'picture' (val) {
      this.abc=[]
      for (let row of val) {
        row.name=`${row.name}${this.idx+1}`
        this.abc.push(row)
      }
      this.$dispatch('picture', this.abc)
    },
    'result' (val) {
      this.$dispatch('result', val)
    },
    'deviceCollects' (val) {
      this.$dispatch('deviceCollects', val)
    },
    'hasDevice' (val) {
      this.$dispatch('hasDevice', val)
    }
  }
}
</script>
