<template>
    <div>
        <criteria-paged :model="model" v-ref:paged>
            <criteria partial='criteria' class="search_area" @condition-changed='$parent.search' v-ref:criteria>
                <div novalidate class="form-horizontal select-overspread container-fluid auto" partial>
                    <div class="row">
                      <div class="col-sm-4" style="width: 20%">
                        <label class="font_normal_body">用户编号</label>
                        <input type="text" class="input_search" v-model="model.f_userinfo_code" id="f_userinfo_code" style="width:60%;"
                               placeholder="用户编号" condition="f_userinfo_code like '%{}%'">
                      </div>
                      <div class="col-sm-4" style="width: 20%">
                        <label class="font_normal_body">用户姓名</label>
                        <input type="text" class="input_search" v-model="model.f_user_name" id="f_user_name" style="width:60%;"
                               placeholder="用户姓名" condition="f_user_name like '%{}%'">
                      </div>
                      <div class="col-sm-4" style="width: 20%">
                        <label class="font_normal_body">起始时间</label>
                            <datepicker
                                    placeholder='起始时间' style="width:60%"
                                    :disabled-days-of-week="[]"
                                    :format="'yyyy-MM-dd'"
                                    :show-rest-button="reset"
                                    :value.sync="model.f_start_time"
                                    v-model="model.f_start_time"
                                    condition="f_offsite_time >= '{} 00:00:00'">
                            </datepicker>
                        </div>
                      <div class="col-sm-4" style="width: 20%">
                        <label class="font_normal_body">结束时间</label>
                        <datepicker
                          placeholder='结束时间' style="width:60%"
                          :disabled-days-of-week="[]"
                          :format="'yyyy-MM-dd'"
                          :show-rest-button="reset"
                          :value.sync="model.f_end_time"
                          v-model="model.f_end_time"
                          condition="f_offsite_time <= '{} 23:59:59'">
                        </datepicker>
                      </div>
                      <div class="col-sm-4" style="width: 20%">
                        <div class="span" style="float: right;margin-top: 8px">
                              <export-excel   :data="{condition: $parent.$parent.model.condition,f_filialeids:$parent.$parent.model.f_filialeids,itemname:$parent.$parent.model.itemname,itemprocessing:$parent.$parent.model.itemprocessing,res:$parent.$parent.model.res,f_defect_content:$parent.$parent.model.f_defect_content}"
                                              :field="$parent.$parent.getfield"
                                              sqlurl="api/af-safecheck/logic/exportfile" sql-name="GetCheckPaperByDefect" :template-name='$parent.$parent.excelTitle' :choose-col="true"></export-excel>

                              <button class="button_search button_spacing" @click="search">查询</button>
                              <button class="button_search button_spacing" @click="$parent.$parent.showmod()">转维修</button>
                                <div style="float: right" class="button_spacing"
                                     :class="{'button_shrink_left':$parent.$parent.$parent.showItem,'button_shrink_right':!$parent.$parent.$parent.showItem}"
                                     @click="$parent.$parent.hiddenr()"></div>
                                <div style="float: right" class="button_spacing"
                                     :class="{'button_shrink_top':$parent.$parent.criteriaShow,'button_shrink_bottom':!$parent.$parent.criteriaShow}"
                                     @click="$parent.$parent.hidden()"></div>
                            </div>
                        </div>
                    </div>
                    <div class="row" v-if="$parent.$parent.criteriaShow">
                      <div class="col-sm-4" style="width: 20%">
                        <label class="font_normal_body">安检计划</label>
                        <input type="text" class="input_search" v-model="$parent.$parent.f_check_plan.f_plan_name"
                               @click="$parent.$parent.showChooser"
                               style="width: 60%" placeholder="安检计划" readonly="readonly">
                      </div>
                      <div class="col-sm-4" style="width: 20%">
                        <label class="font_normal_body">存在隐患</label>
                        <v-select style="width:60% "
                                  class="select select_list"
                                  :value.sync="model.f_has_defect"
                                  v-model="model.f_has_defect"
                                  :options='$parent.$parent.hasDefectOptions'
                                  :placeholder='model.f_has_defect'
                                  condition="f_has_defect = '{}'"
                                  close-on-select>
                        </v-select>
                      </div>
                      <div class="col-sm-8" style="width: 40%">
                        <role-selector
                                    role-name="安检员"
                                    role-lable="安&nbsp;检&nbsp;员&nbsp;"
                                    @re-res="$parent.$parent.getRes"
                                    :value.sync="model.f_checker_id"
                                    v-model="model.f_checker_id"
                                    condition="f_checker_name = '{}'">
                            </role-selector>
                        </div>
                      <div class="col-sm-4" style="width: 20%">
                        <label class="font_normal_body">隐患级别</label>
                        <v-select style="width:60% "
                                  class="select select_list"
                                  :value.sync="model.f_defect_level"
                                  v-model="model.f_defect_level"
                                  :options='$parent.$parent.DefectLevelOptions'
                                  @change="$parent.$parent.setDefectList"
                                  :value-single="true"
                                  placeholder='隐患级别'
                                  close-on-select>
                        </v-select>
                      </div>
                    </div>
                  <div class="row" v-if="$parent.$parent.criteriaShow">
                    <div class="col-sm-4" style="width: 20%">
                      <label class="font_normal_body">隐患选择</label>
                      <v-select style="width:60% "
                                class="select select_list"
                                :value.sync="model.f_item_name"
                                v-model="model.f_item_name"
                                :options='$parent.$parent.defectlist'
                                :value-single="true"
                                placeholder='隐患选择'
                                close-on-select>
                      </v-select>
                    </div>
                    <div class="col-sm-4" style="width: 20%">
                      <label class="font_normal_body">用户类型</label>
                      <v-select style="width:60% "
                                class="select select_list"
                                :value.sync="model.f_check_type"
                                v-model="model.f_check_type"
                                :options='$parent.$parent.usertypes'
                                placeholder='用户类型'
                                :value-single="true"
                                condition="f_check_type = '{}'"
                                close-on-select>
                      </v-select>
                    </div>
                    <div class="col-sm-4" style="width: 20%">
                      <label class="font_normal_body">整改方式</label>
                      <v-select style="width:60% "
                                :value-single="true"
                                class="select select_list"
                                :value.sync="model.f_processing"
                                v-model="model.f_processing"
                                :options='$parent.$parent.f_processings'
                                placeholder='整改方式'
                                close-on-select>
                      </v-select>
                    </div>
                    <div class="col-sm-4" style="width: 20%">
                      <label class="font_normal_body">需转维修</label>
                      <v-select style="width:60% "
                                class="select select_list"
                                :value.sync="model.f_repaired"
                                v-model="model.f_repaired"
                                :options='$parent.$parent.f_repaireds'
                                placeholder='需转维修'
                                :value-single="true"
                                condition="f_repaired = '{}'"
                                close-on-select>
                      </v-select>
                    </div>
                  </div>
                </div>
            </criteria>
            <data-grid :model="model" partial='list' v-ref:grid class="list_area table_sy">
                <template partial='head'>
                    <tr>
                      <th><nobr><input type="checkbox" v-model="$parent.$parent.$parent.checkAll"/> 全选</nobr></th>
                        <th><nobr>入户状态</nobr></th>
                        <th><nobr>用户名</nobr></th>
                        <th><nobr>用户编号</nobr></th>
                        <th><nobr>用户地址</nobr></th>
                        <th><nobr>安检时间</nobr></th>
                        <th><nobr>安检员</nobr></th>
                        <th><nobr>计划名</nobr></th>
                        <th><nobr>是否有隐患</nobr></th>
                        <th><nobr>维修情况</nobr></th>
                        <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;white-space:nowrap;">
                    <!--  当安检单存在未处理的隐患（排除现场处理和用户自行处理的数据）并且对应的安检结果中还存在需转维修的隐患项的时候才显示勾选框 -->
                    <input type="checkbox" v-if="row.f_repaired=='未修'"
                           onClick="event.cancelBubble = true"  @change="$parent.$parent.$parent.setCheckes(row.id)"
                           :checked="$parent.$parent.$parent.isChecked(row.id)" />
                  </td>
                  <td style="text-align: center;white-space:nowrap;">{{row.f_entry_status}}</td>
                    <td style="text-align: center;white-space:nowrap;">{{row.f_user_name}}</td>
                    <td style="text-align: center;white-space:nowrap;">{{row.f_userinfo_code}}</td>
                    <td style="text-align: center;white-space:nowrap;">{{row.f_address}}</td>
                    <td style="text-align: center;white-space:nowrap;">{{row.f_offsite_time}}</td>
                    <td style="text-align: center;white-space:nowrap;">{{row.f_checker_name}}</td>
                    <td style="text-align: center;white-space:nowrap;">{{row.f_plan_name}}</td>
                    <td style="text-align: center;white-space:nowrap;">{{row.f_has_defect}}</td>
                    <td style="text-align: center;white-space:nowrap;">{{row.f_repaired}}</td>
                    <td style="text-align: center;white-space:nowrap;">{{row.defect_content}}</td>
                    <td style="text-align: center;white-space:nowrap;">{{row.f_defect_count}}</td>
                    <td style="text-align: center;white-space:nowrap;">{{row.f_one_count}}</td>
                    <td style="text-align: center;white-space:nowrap;">{{row.f_two_count}}</td>
                    <td style="text-align: center;white-space:nowrap;">{{row.f_three_count}}</td>
                    <td style="text-align: center;white-space:nowrap;">{{row.f_four_count}}</td>
                </template>
            </data-grid>
        </criteria-paged>

        <modal :show.sync="showModal" v-ref:modal>
            <div slot="modal-header" class="modal-header">
                <h4 class="modal-title">
                    选择计划
                </h4>
            </div>
            <div slot="modal-body" class="modal-body">
                <plan-chooser :f.sync="this.$login.f" v-ref:chooser></plan-chooser>
            </div>
            <div slot="modal-footer" class="modal-footer" style="text-align: center">
                <button class="button_search" @click="ok">确认</button>
                <button class="button_search" @click="cancel">取消</button>
            </div>
        </modal>
      <modal :show.sync="showModal2" :backdrop="false">
        <div slot="modal-header" class="modal-header">
          <h4 class="modal-title">
            转维修
          </h4>
        </div>
        <div slot="modal-body" class="modal-body">
          <div v-if="true">
            <div class="row" style="margin-top: 10px">
              <label class="control-label font text-left" style="float:left;margin-left:20%;margin-top:5px">派发类型</label>
              <div class="col-xs-8 col-md-8">
                <v-select :value.sync="selectData.dispatchType" :value-single="true" v-model="selectData.dispatchType"
                          :options='dispatchTypeOptions' placeholder='派发类型'
                          close-on-select>
                </v-select>
              </div>
            </div>
            <div class="row" style="margin-top: 10px" v-if="selectData.dispatchType=='派发给维修员'">
              <label class="control-label font text-left" style="float:left;margin-left:20%;margin-top:5px">维&ensp;修&ensp;员</label>
              <div class="col-xs-8 col-md-8">
                <v-select
                  :value.sync="selectData.f_repairman"
                  :value-single="true"
                  :options='repairers'
                  placeholder='请选择维修员'
                  close-on-select></v-select>
              </div>
            </div>
            <div class="row" style="margin-top: 10px" v-if="selectData.dispatchType=='派发给站点'">
              <label class="control-label font text-left" style="float:left;margin-left:20%;margin-top:5px">站&ensp;&ensp;&ensp;&ensp;点</label>
              <div class="col-xs-8 col-md-8">
                <right-tree
                  islist
                  :userid="userid"
                  :source="'dep=this.getParentByType($organization$).getSpecialResByType($department$),tool.getFullTree(dep.where(row.hasSpecialRole($派单员$)))'"
                  @re-res="getSiteRes"></right-tree>
              </div>
            </div>
            <div class="row" style="margin-top: 10px">
              <label class="control-label font text-left" style="float:left;margin-left:20%;margin-top:5px">报修类型</label>
              <div class="col-xs-8 col-md-8">
                <v-select :value.sync="selectData.f_repairtype" style="width:60%"
                          class="select select_list"
                          :value-single="true"
                          :options='repairTypeOptions'
                          close-on-select>
                </v-select>
              </div>
            </div>
            <div class="row" style="margin-top: 10px">
              <label  class="control-label font text-left" style="float:left;margin-left:20%;margin-top:5px">备&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;注</label>
              <div class="col-xs-8 col-md-8">
                <textarea style="width: 60%; height: 100px" v-model="selectData.f_remarks"></textarea>
              </div>
            </div>
          </div>
        </div>
        <div slot="modal-footer" class="modal-footer" style="text-align: center">
          <button class="button_search" @click="rectification">转维修</button>
          <button class="button_search" @click="cancel1">取消</button>
        </div>
      </modal>
    </div>
</template>
<script>
  import {HttpResetClass, PagedList} from 'vue-client'
  import * as Util from '../Util'

  export default {
    title: '隐患查询',
    data() {
      let model = new PagedList('api/af-safecheck/sql/GetCheckPaperByDefect', 20, {
        f_filialeids: 'this.f_filialeids',
        itemname:'this.itemname',
        res:'this.res',
        f_defect_content: 'this.f_defect_content',
        itemprocessing: 'this.itemprocessing'
      })
      model.f_filialeids = `('${this.$login.f.orgid}')`
      model.itemname='1=1'
      model.f_defect_content="CASE WHEN CHARINDEX( '\"result\":\"正常\"', f_defect_content ) > 0 THEN '无隐患' ELSE replace(replace(replace( replace( RIGHT ( f_defect_content, len( f_defect_content ) - 26 ), substring('{}',2,1), '' ), substring('{}',1,1), '' ),']',''),'\"','') END"
      model.res= `{"result":"正常","data":[]}`
      model.itemprocessing= `1=1`
      return {
        excelTitle:'隐患结果查看导出'+Util.toStandardTimeString().substring(11,19).replace(new RegExp( ':' , "g" ),""),
        hasDefectOptions: [{label: '全部', value: ''}, {label: '有隐患', value: '有隐患'}, {label: '无隐患', value: '无隐患'}],
        DefectLevelOptions: [{label: '全部', value: ''}, {label: '一级隐患', value: 'f_one_count>0'}, {label: '二级隐患', value: 'f_two_count>0'}, {label: '三级隐患', value: 'f_three_count>0'}],
        f: this.$login.f,
        usertypes: [{label: '全部', value: ''}, {label: '民用', value: '民用'}, {label: '非民用', value: '非民用'}],
        f_repaireds: [{label: '无需转维修', value: ''}, {label: '需转维修', value: '未修'}],
        model: model,
        criteriaShow: false,
        showModal: false,
        f_check_plan: {f_plan_name: '', id: ''},
        sumsmodel: {},
        all: false,
        showModal2:false,
        checkAll:false,
        checkes:[],
        repairTypeOptions:this.$appdata.getParam('报修类型'),
        dispatchTypeOptions: [{label: '派发给维修员', value: '派发给维修员'}],
        selectData:{
          dispatchType:'',
          f_repairman:'',
          f_remarks:'',
          f_repairtype:''
        },
        f_processings:[{label: '全部', value: ''},{label: '现场处理', value: '现场处理'},{label: '用户自行处理', value: '用户自行处理'},{label: '需转维修处理', value: '需转维修处理'}],
        userid:this.$login.f.id,
        fields: {},
        modelval: [],
        defectlist:[],
        repairers: [],
        thead: '',
        headData: ['入户状态','用户名','用户编号','用户地址','安检时间','安检员','计划名','是否有隐患','维修情况','隐患原因','隐患数','一级隐患数','二级隐患数','三级隐患数','气量异常差值'],
        bodyData: ['f_entry_status','f_user_name','f_userinfo_code','f_address','f_offsite_time','f_checker_name','f_plan_name','f_has_defect','f_repaired','defect_content','f_defect_count','f_one_count','f_two_count','f_three_count','f_four_count']
      }
    },
    methods: {
      cancel1(){
        this.showModal2=false
        this.selectData={
          dispatchType:'',
          f_repairman:'',
          f_remarks:'',
          f_repairtype:''
        }
      },
      showmod(){
        if(this.model.rows.length==0){
          this.$showMessage('请先选择需要转维修的用户！')
          return
        }
        if (this.checkAll  ||  this.checkes.length>0) {
          this.showModal2=true
        }else{
          this.$showMessage('请先勾选需要转维修的用户！')
          return
        }

      },
      rectification(){
        if(this.selectData.dispatchType){
          if(this.selectData.dispatchType=='派发给站点'){
            if(!this.selectData.f_reciever){
              this.$showMessage('请选择部门！')
              return
            }
          }else{
            if(!this.selectData.f_repairman){
              this.$showMessage('请选择维修员！')
              return
            }
          }
        }else {
          this.$showMessage('请选择派发类型！')
          return
        }
        if(!this.selectData.f_repairtype){
          this.$showMessage('请选择报修类型！')
          return
        }
        this.$showMessage('确定要将当前选中用户转派给维修吗？！', ['confirm', 'cancel']).then((msg)=>{
          if(msg=='confirm'){

              let act={}
              let toRepair=''
              if(this.selectData.dispatchType=='派发给站点'){
                act={f_meetunit:this.selectData.f_meetunit,f_reciever:this.selectData.f_reciever,f_service_acitivity_type:'派单'}
                toRepair=null
              } else {
                console.log('派发给维修员---------'+this.selectData.f_repairman)
                act={f_meetunit:'',f_reciever:this.selectData.f_repairman,f_service_acitivity_type:'派单'}
                toRepair='一级派单'
              }
              this.$resetpost(`/api/af-safecheck/logic/UploadRectification`,
                {
                  condition:this.model.params.condition,
                  itemname:this.model.itemname,
                  itemprocessing:this.model.itemprocessing,
                  res:this.model.res,
                  f_defect_content:this.model.f_defect_content,
                  f_filialeids:this.model.params.f_filialeids,
                  switchCheckAll:true,
                  checkAll:this.checkAll,
                  param:this.checkes,
                  columnName:'id',
                  toRepair:toRepair,
                  activity:act,
                  deps:this.$login.f.deps,
                  f_remarks:this.selectData.f_remarks,
                  f_repairtype:this.selectData.f_repairtype,
                  f_attendant: this.$login.f.name,
                  loginUser:{name:this.$login.f.name,ename:this.$login.f.ename},
                },{resolveMsg: null, rejectMsg: null}).then((res) => {
                if(res.data.code=200){
                  //this.$showMessage('本次成功派发'+res.data.successcon+'个维修单！'+`其中${res.data.nohidden}个不需要隐患整改,${res.data.repeatCount}个已经派发过隐患整改单`)
                  this.$showMessage('本次成功派发'+res.data.successcon+'个维修单！')
                  this.checkAll=false;
                  // 全选改变后，清空选中数据
                  this.checkes = []
                  this.selectData={
                    dispatchType:'',
                      f_repairman:'',
                      f_remarks:'',
                      f_repairtype:''
                  }
                  this.showModal2=false
                  this.$refs.paged.$refs.criteria.search()
                }
              }).cache((msg)=>{
                this.$showMessage('网络异常，请重新操作！')
              })
          }
        })
      },
      getSiteRes(obj) {
        console.log('siteRes ---> ')
        console.log(obj)
        if(obj.resids[0]){
          this.selectData.f_meetunit = obj.res.join('.')
          this.selectData.f_reciever = obj.resids.join('.')
          this.selectData.f_outlets = obj.res[obj.res.length - 1]
        }else {
          this.selectData.f_meetunit = ''
          this.selectData.f_reciever = ''
          this.selectData.f_outlets = ''
        }
      },
      // 获取维修员
      getEmp() {
        let val = {source: 'this.getParentByType($organization$).getSpecialResByType($user$).where(row.getAttributes().get($rolestr$)!=null ).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) => {
          let str=''
          res.data.forEach((item) => {
            this.repairers.push({label: item.name, value: item.name})
          })
        })
      },
      isChecked(v) {
        // 如果全选，不在的按选中算，否则，在的按选中算
        if (this.checkAll) {
          return this.checkes.indexOf(v) == -1
        } else {
          return this.checkes.indexOf(v) != -1
        }
      },
      setCheckAll() {
        this.checkAll=this.checkAll?false:true;
        // 全选改变后，清空选中数据
        this.checkes = []
      },
      setCheckes(id) {
        let index=this.checkes.indexOf(id)
        if(index<0){
          this.checkes.push(id)
        }else{
          this.checkes.splice(index,1)
        }
      },
      setDefectList(val){
        console.log("555555555555")
        console.log(val)
        if (val=='f_one_count>0'){
          console.log("111111")
          this.defectlist=[{label: '全部', value: ''}, ...this.$appdata.getParam('一级隐患')]
        }else if (val=='f_two_count>0'){
          console.log("1111112")
          this.defectlist=[{label: '全部', value: ''}, ...this.$appdata.getParam('二级隐患')]
        }else if (val=='f_three_count>0'){
          console.log("1111113")
          this.defectlist=[{label: '全部', value: ''}, ...this.$appdata.getParam('三级隐患')]
        }else{
          this.defectlist=[{label: '全部', value: ''}]
        }

        console.log(this.defectlist)
      },
      hiddenr() {
        this.$parent.showItem = !this.$parent.showItem
      },
      hidden() {
        this.criteriaShow = !this.criteriaShow
      },
      search(args) {
        if (this.$refs.paged.$refs.criteria.model.f_defect_level){
          console.log(this.$refs.paged.$refs.criteria.model.f_defect_level)
          args.condition += ` and ${this.$refs.paged.$refs.criteria.model.f_defect_level}`
        }
        if (this.$refs.paged.$refs.criteria.model.f_item_name){
          console.log(this.$refs.paged.$refs.criteria.model.f_item_name)
          this.model.itemname = ` cp.f_defect_content like '%${this.$refs.paged.$refs.criteria.model.f_item_name}%'`
        }
        if (this.$refs.paged.$refs.criteria.model.f_processing!==''){
          console.log(this.$refs.paged.$refs.criteria.model.f_item_name)
          this.model.itemprocessing = ` f_processing = '${this.$refs.paged.$refs.criteria.model.f_processing}'`
        } else {
          this.model.itemprocessing = ' 1=1 '
        }
        if (this.f_check_plan.f_plan_name) {
          args.condition += ` and f_check_plan_id = '${this.f_check_plan.id}'`
        }
        this.model.search(args.condition, args.model)
      },
      getRes(obj) {
        this.model.f_filialeids = this.$login.convertToIn(obj.resids);
        console.log(this.model.f_filialeids)
      },
      showChooser() {
        this.showModal = true
      },
      ok() {
        this.showModal = false
        if (this.$refs.modal.$children[0].selectedRow.id) {
          this.f_check_plan = this.$refs.modal.$children[0].selectedRow
        }
      },
      cancel() {
        this.showModal = false
        this.f_check_plan = {f_plan_name: '', id: ''}
      }
    },
    ready() {
      console.log()
      this.$refs.paged.$refs.criteria.model.f_has_defect = '有隐患'
      this.$refs.paged.$refs.criteria.model.f_end_time=Util.toStandardTimeString().substring(0,10)
      this.$refs.paged.$refs.criteria.model.f_start_time=Util.getPreMonth(this.$refs.paged.$refs.criteria.model.f_end_time)
      this.getEmp()

    },
    computed: {
      selected() {
        return this.$refs.paged.$refs.grid.selected
      },
      getfield(){
        console.log("---------------------------------------------导出方法")
        let data = {}
        this.bodyData.forEach((value, index)=>{
          data[this.bodyData[index]] = this.headData[index]
        })
        //合计字段打印
        this.tfoot = `<tr><th colspan=${this.modelval.length}>全表汇总信息: `
        if(this.sumsmodel){
          Object.keys(this.sumsmodel).forEach((key) => {
            this.tfoot += this.fields[key] + '合计: ' + `<font color="blue">${this.sumsmodel[key]} </font>`
          })
        }else{
          this.tfoot += '暂无'
        }
        this.tfoot += '</th></tr>'
        return data
      }
    },
    watch:{

    }
  }
</script>
