<template>
  <div style="height: 100%">
    <div class="panel auto">
      <div  class="panel-body ">
        <div class="row auto" style="margin: 5px 0">
          <label class="righttxt" style="width: 30%;">负责人姓名:</label>
          <input v-model="bindingData.f_head_name" class="form-control rightipt" type="text"/>
        </div>
      </div>
    </div>
    <div class="panel auto">
      <div  class="panel-body ">
        <div class="row auto" style="margin: 5px 0">
          <label class="righttxt" style="width: 30%;">负责人职务:</label>
          <v-select v-model="bindingData.f_head_post" :options='headPostTypes' :value.sync="bindingData.f_head_post" :width="'60%'"
                    class="input-font" clear-button close-on-select placeholder='类型' style="margin-left: 5%;"
                    value-single></v-select>
        </div>
      </div>
    </div>
    <div class="panel auto">
      <div  class="panel-body ">
        <div class="row auto" style="margin: 5px 0">
          <label class="righttxt" style="width: 30%;">负责人电话:</label>
          <input v-model="bindingData.f_head_phone" class="form-control rightipt" type="text"/>
        </div>
      </div>
    </div>
    <div class="panel auto">
      <div  class="panel-body ">
        <div class="row auto" style="margin: 5px 0">
          <label class="righttxt" style="width: 30%;">绑定类型:</label>
          <v-select v-model="bindingData.f_type" :options='types' :value.sync="bindingData.f_type" :width="'60%'"
                    class="input-font" clear-button close-on-select placeholder='类型' style="margin-left: 5%;"
                    value-single></v-select>
        </div>
      </div>
    </div>
    <div v-if="bindingData.f_type == '小区'" class="panel auto">
      <div  class="panel-body ">
        <div class="row auto" style="margin: 5px 0">
          <label class="righttxt" style="width: 30%;">小区名称:</label>
          <v-select v-model="bindingData.f_userinfo" :options='residentialAreas' :value.sync="bindingData.f_userinfo" :width="'60%'"
                    class="input-font" clear-button close-on-select placeholder='小区名称'
                    style="margin-left: 5%;" value-single></v-select>
        </div>
      </div>
    </div>
    <div v-if="bindingData.f_type == '用户'" class="panel auto">
      <div  class="panel-body ">
        <div class="row auto" style="margin: 5px 0">
          <label class="righttxt" style="width: 30%;">用户名称:</label>
          <v-select v-model="bindingData.f_userinfo" :options='userNames' :value.sync="bindingData.f_userinfo" :width="'60%'"
                    class="input-font" clear-button close-on-select placeholder='用户名称' @select-search="refreshUser"
                    style="margin-left: 5%;" menu-mode="align-button"
                    value-single></v-select>
        </div>
      </div>
    </div>
    <div class="panel auto">
      <div class="panel-body">
        <label class="row auto text-left col-md-4 col-xs-4">备注</label>
        <div class="col-md-12 col-sm-12 col-xs-12">
          <textarea v-model="bindingData.f_comments" class="form-control"></textarea>
        </div>
      </div>
    </div>
    <div class="panel auto">
      <div  class="panel-body ">
        <div class="row auto" style="margin: 5px 0">
          <label class="righttxt">图片:</label>
          <div class="col-xs-6" style="height: 160px;width:160px;overflow: scroll;top: 1px">
            <img-self v-if="bindingData.f_head_pic" :src="bindingData.f_head_pic" width="140" height="140"></img-self>
            <button v-if="!bindingData.f_head_pic" type="button" name="button" class="btn btn-primary" @click="takePictures('com.aofeng.hybrid.android.peripheral.CameraActivity')">拍照</button>
            <button v-if="!bindingData.f_head_pic" type="button" name="button" class="btn btn-primary" @click="takePictures('com.aofeng.hybrid.android.peripheral.ActionMultiplePickActivity')">相册</button>
          </div>
        </div>
      </div>
    </div>
    <div class="panel auto">
      <div class="panel-body">
        <div style="display: flex;justify-content: center;">
          <button class="col-sm-3 btn btn-primary" @click="binding()">绑定</button>
        </div>
      </div>
    </div>
  </div>
</template>

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


export default {
  title: '二维码绑定',
  data() {
    return {
      bindingData: {},
      residentialAreas: [{label: '请选择', value: ''}],
      userNames: [{label: '请选择', value: ''}],
      headPostTypes:[{label: '请选择', value: ''} ,...this.$appdata.getParam('负责人职务')],
      types: [{label: '请选择', value: ''}, {label: '小区', value: '小区'}, {label: '用户', value: '用户'}]
    }
  },
  props: {
    row: {
      type: Object
    }
  },
  methods: {
    async fetchUsers(condition) {
      try {
        const response = await new HttpResetClass().load('post', `${this.$androidUtil.getProxyUrl()}/rs/sql/tel_singleTable_OrderBy`, {
          data: {
            items: 'ui.f_user_name,ui.f_userinfo_id,ui.f_userinfo_code',
            tablename: 't_userinfo ui LEFT JOIN t_userfiles uf on ui.f_userinfo_id = uf.f_userinfo_id',
            condition: condition,
            orderitem: '1'
          }
        });
        return response.data;
      } catch (error) {
        return [];
      }
    },
    async refreshUser(val) {
      let condition = `1=1 and f_user_name is not null and uf.f_user_type = '非民用' and uf.f_table_state in ('正常','停用') and (ui.f_user_name like '${val}%' or ui.f_userinfo_code like '${this.bindingData.f_userinfo_code}%')`;
      const users = await this.fetchUsers(condition);
      users.forEach(item => {
        if (!this.userNames.some(user => user.value.f_userinfo_id == item.f_userinfo_id)) {
          this.userNames.push({ label: `${item.f_user_name}:${item.f_userinfo_code}`, value: item })
        }
      })
    },
    cameraCallBack(prop,fileName) {
      this.$set('bindingData.f_head_pic',fileName)
    },
    takePictures(page){
      HostApp.__callback__ = this.cameraCallBack
      HostApp.__this__ = this
      let prop = 'QRCode'
      this.fileName = Util.guid() +'.jpg'
      HostApp._open_a_page({
        type: 'boomerang',
        page: page,
        param: {
          file: this.fileName,
          requestCode: 111,
          callback: 'javascript:HostApp.__callback__("' + prop + '", "%s");',
          watermark: ''
        }
      })
    },
    async binding() {
      if (!this.bindingData.f_head_pic){
        this.$showMessage('请上传图片')
        return
      }
      let tableImages = []
      if (!this.row.f_head_pic){
        tableImages.push({
          path:this.bindingData.f_head_pic
        })
      }
      let data = {
        tableImages: tableImages
      }
      HostApp.__this__ = this
      HostApp.logicWithHint({
        'logic': 'imagesUploadAndroid', 'callback': 'javascript: HostApp.__this__.commitCallBack()',
        'data': data, 'backresult': 1
      })
    },
    async commitCallBack(jo) {
      if (jo.state == 'ok') {
        if (this.bindingData.f_userinfo && this.bindingData.f_type == '用户'){
          this.bindingData.f_user_name = this.bindingData.f_userinfo.split(':')[0].trim()
          this.bindingData.f_userinfo_id = this.bindingData.f_userinfo.split(':')[1].trim()
        }else if (this.bindingData.f_userinfo && this.bindingData.f_type == '小区') {
          this.bindingData.f_user_name = this.bindingData.f_userinfo.split(':')[0].trim()
          this.bindingData.f_userinfo_id = this.bindingData.f_userinfo.split(':')[1].trim()
        }
        const res = JSON.parse(jo.result)
        let sql = ''
        if (res.images && res.images.length > 0){
          sql = `update t_qr_code set f_head_name = '${this.bindingData.f_head_name}',f_head_post = '${this.bindingData.f_head_post}',f_head_phone = '${this.bindingData.f_head_phone}',f_type = '${this.bindingData.f_type}',f_user_name = '${this.bindingData.f_user_name}',f_userinfo_id = '${this.bindingData.f_userinfo_id}',f_comments = '${this.bindingData.f_comments}',f_head_pic='${res.images[0].imgfileName}' where id = '${this.bindingData.id}'`
        }else {
          sql = `update t_qr_code set f_head_name = '${this.bindingData.f_head_name}',f_head_post = '${this.bindingData.f_head_post}',f_head_phone = '${this.bindingData.f_head_phone}',f_type = '${this.bindingData.f_type}',f_user_name = '${this.bindingData.f_user_name}',f_userinfo_id = '${this.bindingData.f_userinfo_id}',f_comments = '${this.bindingData.f_comments}' where id = '${this.bindingData.id}'`
        }
        new HttpResetClass().load('POST', `${this.$androidUtil.getProxyUrl()}/rs/logic/runSQL`, {data: {sql: sql}}).then(()=>{
          this.$showMessage('绑定成功')
          this.$dispatch('confirm')
        }).catch(()=>{
          this.$showMessage('绑定失败')
        })
      }else {
        this.$showMessage('图片上传失败')
      }
    },
  },
  async ready() {
    this.bindingData = JSON.parse(JSON.stringify(this.row))
    if(this.bindingData.f_head_pic && !this.bindingData.url){
      this.bindingData.f_head_pic = `${this.$androidUtil.getProxyUrl()}/rs/image/file/${this.bindingData.f_head_pic}`
    }
    if (this.bindingData.url && !this.bindingData.f_head_pic){
      this.bindingData.f_head_pic = `${this.$androidUtil.getProxyUrl()}${this.bindingData.url}`
    }
    if (this.bindingData.f_head_pic && this.bindingData.url){
      this.bindingData.f_head_pic = `${this.$androidUtil.getProxyUrl()}${this.bindingData.url}`
    }
    let residentialArea = await new HttpResetClass().load('post', `${this.$androidUtil.getProxyUrl()}/rs/sql/tel_singleTable_OrderBy`, {
      data: {
        items: 'f_residential_area,id',
        tablename: 't_area',
        condition: `1=1 and f_residential_area is not null`,
        orderitem: '1'
      }
    })
    residentialArea.data.forEach(item => {
      if (item.id == this.bindingData.f_userinfo_id){
        this.bindingData.f_userinfo = `${item.f_residential_area}:${item.id}`
      }
      this.residentialAreas.push({label: item.f_residential_area, value: `${item.f_residential_area}:${item.id}`});
    })
    const users = await this.fetchUsers(`1=1 and f_user_name is not null and uf.f_user_type = '非民用' and uf.f_table_state in ('正常','停用')`)
    users.forEach(item => {
      if (this.bindingData.f_userinfo_id == item.f_userinfo_code){
        this.bindingData.f_userinfo = `${item.f_user_name}:${item.f_userinfo_code}`
      }
      this.userNames.push({ label: `${item.f_user_name}:${item.f_userinfo_code}`, value: `${item.f_user_name}:${item.f_userinfo_code}` })
    })
  }
}
</script>
<style lang="less" scoped>
.butt3 {
  float: right;
  width: 12px;
  margin: 1% 2% 0 0;
}

.rightipt {
  width: 60%;
  float: left;
  margin-left: 5%;
}

.righttxt {
  border: none;
  margin-left: 5px;
  /*border-left: 5px solid #A2C2EB;*/
  float: left;
  width: 25%;
  margin-bottom: 3px;
  text-align: left;
  word-wrap: break-word;
  white-space: normal;
}

.spanboder {
  border-bottom: 2px solid #499edf;
  padding-bottom: 8px
}

#upuserinfo_sel /deep/ ul {
  width: 100% !important;
  left: 0 !important;
}

.btn-photo {
  border: 0;
  border-radius: 7px;
  background-color: #7dc1f4;
  font: 15px PingFang-SC-Bold;
  height: 20%;
}

.panel-self {
  border-radius: 10px;
  border: 1px solid #499EDF;
  background-color: #F8F8F8;
}

.div-photo {
  width: auto;
  height: auto;
  /* margin-top: 10px; */
  position: absolute;
  bottom: 10px;
  right: 10px;
}
</style>
<style lang="less">
#upuserinfo_sel ul {
  width: 100% !important;
  left: 0 !important;
}
</style>
