<template>
  <div style="flex:1;" class="flex">
    <button class="btn btn-xs" v-show="!criteriaShow" @click="show()">
      <span class="glyphicon glyphicon-chevron-down" style="color: #000;"></span>
    </button>
    <criteria-paged :model="model"  v-ref:paged>
      <criteria partial='criteria' v-show="$parent.criteriaShow" @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-3 form-group form-input-group" style="width: 20%">
              <label class="control-label">用户编号</label>
              <input type="text" class="form-control" v-model="model.f_userinfo_code" id="f_userinfo_code"
                     placeholder="用户编号" condition="f_userinfo_code like '%{}%'">
            </div>
            <div class="col-sm-3 form-group form-input-group" style="width: 20%">
              <label class="control-label">用户姓名</label>
              <input type="text" class="form-control" v-model="model.f_user_name" id="f_user_name"
                     placeholder="用户姓名" condition="f_user_name like '%{}%'">
            </div>
            <div class="col-sm-3 form-group form-input-group" style="width: 20%">
              <label class="control-label">小区</label>
              <input type="text" class="form-control" v-model="model.f_residential_area" id="f_residential_area"
                     placeholder="小区" condition="f_residential_area like '%{}%'">
            </div>
            <div class="col-sm-3 form-group form-input-group" style="width: 20%">
              <label class="control-label">地址</label>
              <input type="text" class="form-control" v-model="model.f_address" id="f_address"
                     placeholder="地址" condition="f_address like '%{}%'">
            </div>
            <!--<div class="col-sm-3 form-group form-input-group" style="width: 20%">-->
              <!--<label class="control-label">用户类型</label>-->
              <!--<v-select id="f_usertype"-->
                        <!--placeholder='用户类型'-->
                        <!--:value.sync="model.f_usertype"-->
                        <!--:value-single="true"-->
                        <!--:options='$parent.$parent.usertypes'-->
                        <!--v-model="model.f_usertype"-->
                        <!--condition="f_user_type = '{}'"-->
                        <!--close-on-select clear-button> </v-select>-->
            <!--</div>-->
            <div class="col-sm-3 form-group form-input-group" style="width: 20%">
              <label class="control-label" style="color: red;">安检筛选</label>
              <v-select
                placeholder='安检筛选'
                :value-single="true"
                :value.sync="$parent.$parent.SafeCheckXZ"
                :options='$parent.$parent.SafeCheckXZs'
                v-model="$parent.$parent.SafeCheckXZ"
                close-on-select clear-button> </v-select>
            </div>
            <div class="col-sm-3 form-group form-input-group" style="width: 20%">
              <label class="control-label">安检起始</label>
              <datepicker
                :value.sync="model.f_check_start"
                placeholder='最后安检时间起始'
                :disabled-days-of-week="[]"
                :format="'yyyy-MM-dd'"
                :show-rest-button="reset"
                v-model = "model.f_check_start">
              </datepicker>
            </div>
            <div class="col-sm-3 form-group form-input-group" style="width: 20%">
              <label class="control-label">安检结束</label>
              <datepicker
                :value.sync="model.f_check_end"
                placeholder='最后安检时间结束'
                :disabled-days-of-week="[]"
                :format="'yyyy-MM-dd'"
                :show-rest-button="reset"
                v-model = "model.f_check_end">
              </datepicker>
            </div>

            <div class="col-sm-3 form-group form-input-group" style="width: 20%">
              <label class="control-label">安检状态</label>
              <v-select id="f_entry"
                        placeholder='安检状态'
                        :value.sync="model.f_last_check_state"
                        :value-single="true"
                        :options='$parent.$parent.checkstatus'
                        v-model="model.f_last_check_state"
                        condition="f_last_check_state = '{}'"
                        close-on-select clear-button> </v-select>
            </div>
            <div  class="col-sm-3 form-group form-input-group" style="width: 20%">
              <label class="control-label">隐患情况</label>
              <v-select
                placeholder='隐患情况'
                :value-single="true"
                v-model='model.f_check_result'
                :value.sync="model.f_check_result"
                :options='$parent.$parent.f_check_results'
                condition="f_last_check_result  like '%{}%'"
                close-on-select clear-button> </v-select>
            </div>
            <div  class="col-sm-3 form-group form-input-group" style="width: 20%" v-if="$parent.$parent.orgstrs.length > 1">
              <label class="control-label">县域公司</label>
              <v-select
                placeholder='县域分公司'
                :value-single="true"
                v-model='model.f_orgstr'
                :value.sync="model.f_orgstr"
                :options='$parent.$parent.orgstrs'
                condition="f_orgstr like '%{}%'"
                close-on-select clear-button> </v-select>
            </div>
            <div class="row">
              <div class="col-sm-8"></div>
              <div class="col-sm-2">
              </div>
              <div class="col-sm-1">
                <div class="span" style = "float:left;">
                <export-excel   :data="$parent.$parent.searchData"
                                :field="$parent.$parent.excelHeaders"
                                sqlurl="api/af-safecheck/logic/exportfile" sql-name="FetchUserFileByOrgChecker" template-name='用户安检情况'></export-excel>
                </div>

              </div>
              <div class="col-sm-1">
                <div class="span" style = "float:left;">
                  <button class="btn btn-primary width-80" @click="search()">查询</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </criteria>
      <data-grid :model="model" partial="list" class="table table-bordered table table-hover" v-ref:grid>
        <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>
            <th><nobr>地址</nobr></th>
            <th><nobr>安检日期</nobr></th>
            <th><nobr>安检状态</nobr></th>
            <th><nobr>安检结果</nobr></th>
          </tr>
        </template>
        <template partial='body'>
          <td v-bind:class="{newcolor:row.code==1}" style="text-align: center;">{{row.f_userinfo_code}}</td>
          <td v-bind:class="{newcolor:row.code==1}" style="text-align: center;">{{row.f_user_name}}</td>
          <td v-bind:class="{newcolor:row.code==1}" style="text-align: center;">{{row.f_user_phone}}</td>
          <td v-bind:class="{newcolor:row.code==1}" style="text-align: center;">{{row.count_item}}</td>
          <td v-bind:class="{newcolor:row.code=='1'}" style="text-align: center">{{row.f_user_type}}</td>
          <td v-bind:class="{newcolor:row.code==1}" style="text-align: center">{{row.f_residential_area}}</td>
          <td v-bind:class="{newcolor:row.code==1}" style="text-align: center">{{row.f_address}}</td>
          <td v-bind:class="{newcolor:row.code==1}" style="text-align: center">{{row.f_last_check_date}}</td>
          <td v-bind:class="{newcolor:row.code==1}" style="text-align: center">{{row.f_last_check_state}}</td>
          <td v-bind:class="{newcolor:row.code==1}" style="text-align: center">{{$parent.$parent.$parent.getDefect(row.f_last_check_result)}}</td>
        </template>
      </data-grid>
    </criteria-paged>
  </div>
</template>

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

  // let select = function * (self,userid) {
  //   let http = new HttpResetClass()
  //   let getGasman = yield http.load('POST','/rs/search', {
  //     source: 'this.getChildByName($安检员$).getUsers()',
  //     userid: userid
  //   }, {resolveMsg: null, rejectMsg: null})
  //   console.log('获取安检员', getGasman)
  //   getGasman.data.forEach((checker)=>{
  //     self.checkersid.push({label:checker.name,value:checker.id})
  //   })
  //   self.checkersid.push({label:'全部',value:''})
  // }


  export default {
    title: '民用用户安检情况',
    data() {
      let options = []
      let year = (new Date()).getFullYear()
      for (let i = year; i <= year + 3; i++)
        options.push({label: i + '', value: i + ''})
      let moptions = []
      for (let i = 1; i <= 12; i++)
        moptions.push({label: i + '', value: i + ''})

      return {
        searchData: {
          condition: '1=1',
          orderitem: "f_userinfo_code",

          timetype:"dd" ,
          f_filialeids:`(${this.$login.f.orgid})`
        },
        excelHeaders: {
          //用户编号	用户名称	用户电话	安检次数	用户类型	小区名称	地址	安检日期	安检状态	安检结果

          'f_userinfo_code': '用户编号',
          'f_user_name': '用户名称',
          'f_user_phone': '用户电话',
          'count_item':'安检次数',
          'f_user_type': '用户类型',
          'f_residential_area': '小区名称',
          'f_address':'地址',
          'f_last_check_date':'安检日期',
          'f_last_check_state': '安检状态',
          'f_last_check_result':'安检结果'
        },
        model: new PagedList('api/af-safecheck/sql/FetchUserFileByOrgChecker', 20, {orderitem: "'f_userinfo_code'",timetype:"'dd'" ,f_filialeids:`'(${this.$login.f.orgid})'`}),
        orgstrs:[{label: '全部', value: ''}],
        checkersid:[],
        SafeCheckXZ:'',
        civil:'',   //民用安检周期
        civilian:'',      //非民用安检周期
        SafeCheckXZs: [{label: '全部', value: ''},{label: '未安检', value: '未安检'}, {label: '已安检', value: '已安检'}], // 安检筛选选项
        SafeCheckSXs: [{label: '是', value: '是'}, {label: '否', value: '否'}, {label: '全部', value: ''},],
        IsShares: [{label: '是', value: '是'}, {label: '否', value: '否'}],
        IsShare:'否',
        checker: {},
        NoBuys:[{label: '是', value: '是'},{label: '否', value: '否'}],
        criteriaShow: true,
        checkers: [],
        chosenOrg: {id: 0},
        showModal: false,
        checkedAll: false,
        checkrows: [],
        adjustables: [],
        f_plan_year: year + '',
        f_plan_month: moptions[new Date().getMonth()].value,
        f_effective_start_time:'',  //计划有效起始时间
        f_effective_end_time:'',    //计划有效结束时间
        checkboxModel: {},
        c_year_list: options,
        c_month_list: moptions,
        areas: this.areas(),
        checkstatus: this.checkstatus(),
        usertypes: this.usertypes(),
        userstates: this.userstates(),
        sqlname:'',
        f_check_results:  [{label: '全部', value: ''}, {label: '正常', value: '正常'},{label: '有隐患', value: '有隐患'}],
        creatPlanWay:''

      }
    },
    props: {
      checkplan: { // 传入一条安检计划信息
        type: Object
      },
      additemshow:{
        type:Boolean,
        default:false
      }
    },
    ready() {
      // 获取分公司信息
      this.getfengongsi()
      this.model.chosenOrg = {id: 0}
      this.model.f_filialeids = this.$login.f.f_orgids
      this.model.f_filiale = this.$login.f.f_fengongsi
      this.model.f_OrgStr = this.$login.f.orgpathstr
    },
    methods: {
      // 获取县域分公司内容
      getfengongsi(){
        let val = {source: 'this.getParentByType($organization$).getSpecialResByType($organization$)', 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) => {
            this.orgstrs.push({label: item.name, value: item.id})
          })
          console.log(this.orgstrs.length)
        })
      },
      // 县域分公司发生改变
      // orgstrchange(val){
      //   if(val == undefined || val == ''){
      //     return
      //   }else {
      //     this.checkersid = []
      //     let gen = select(this,val)
      //     return co(gen)
      //   }
      // },
      getDefect(val){
        if(val){
          try {
            var defect = JSON.parse(val)
            return defect.result
          }catch (e) {
            console.log(val)
            return '正常'
          }
        }
        return '正常'
      },
      checkerchange(val) {
        this.checkboxModel.f_checker = val.name
        this.checkboxModel.f_checker_id = val.id
      },
      search(args) {
        if(this.SafeCheckXZ && (args.model.f_check_start == '' || args.model.f_check_end == '')){
          this.$showMessage('如果选择 已安检/未安检 选项，需要选择 安检起始时间！')
          return
        }
        if(this.SafeCheckXZ == '未安检'){
          args.condition += " and ( f_last_check_date >= '"+ args.model.f_check_end + "' or  f_last_check_date <= '"+ args.model.f_check_start + "' or f_last_check_date is null)"
        }else{
          if(args.model.f_check_start){
            args.condition += " and f_last_check_date >= '"+ args.model.f_check_start + "'"
          }
          if(args.model.f_check_end){
            args.condition += " and f_last_check_date <= '"+ args.model.f_check_end + "'"
          }
        }
        args.condition += " and f_filialeid =  '" + this.$login.f.orgid + "' and f_user_type='民用'"
        this.searchData.condition=args.condition
        return this.model.search( args.condition, args.model)
      },
      checkstatus() {
        return [{label: '全部', value: ''}, ...this.$appdata.getParam('安检状态')]
      },
      usertypes() {
        return [{label: '全部', value: ''}, ...this.$appdata.getParam('用户类型')]
      },
      userstates() {
        return [{label: '全部', value: ''}, ...this.$appdata.getParam('用户状态')]
      },
      show() {
        this.criteriaShow = true
      },
      hidden() {
        this.criteriaShow = false
      },
      confirm() {
        if (!this.checkboxModel.f_plan_name) {
          this.$showMessage('请填写安检计划名称!')
          return
        }
        // if(this.f_effective_start_time == ''){
        //   this.$showMessage('请选择有效起始日期！')
        //   return
        // }
        // if(this.f_effective_end_time == ''){
        //   this.$showMessage('请选择有效结束日期！')
        //   return
        // }
        if(this.IsShare == '否'){
          if (!this.checkboxModel.f_checker_id) {
            this.$showMessage('请选择安检员！')
            return
          }
        }
        let gen = saveGen(this)
        return co(gen)
      },
      changeStates() {
        if (this.checkedAll) {//实现反选/
          this.checkrows = [];
          for (let i = 0; i < this.$refs.paged.model.rows.length; i++) {
            this.$set('$refs.paged.model.rows[' + i + '].checked', false)
          }
        } else {//实现全选
          for (let i = 0; i < this.$refs.paged.model.rows.length; i++) {
            this.$set('$refs.paged.model.rows[' + i + '].checked', true)
          }
          let _this = this
          let condition = this.$refs.paged.$refs.criteria.condition
          let url = this.model.url
          this.$resetpost(`${url}?pageSize=9999999`, {
            data: {
              condition: condition,
              groupitem: '',
              orderitem: 'f_residential_area',
              f_usertype:this.model.f_usertype,
              f_filialeids: this.model.f_filialeids,
              month: this.model.month,
              safeCycle:this.model.safeCycle,
              f_checktime_start:this.model.f_checktime_start,
              f_checktime_end:this.model.f_checktime_end,
              SafeCheckSX: this.model.SafeCheckSX,
              f_last_check_state: this.model.f_last_check_state
            },
          },{resolveMsg: null, rejectMsg: null}, -1).then(
            (respanse) => {
              if (respanse.data.length >= 5000) {
                this.$showMessage("数据量太大，请重新选择")
              } else {
                _this.checkrows = []
                for (let j = 0; j < respanse.data.length; j++) {
                  _this.checkrows.push(respanse.data[j])
                }
                console.log(_this.checkrows);
              }
            })
        }
      },
      addChecked(item) {
        console.log(item);
        if (!item.checked) {
          this.checkrows.push(item);
          console.log(this.checkrows);
        } else {
          for (let i = 0; i < this.checkrows.length; i++) {
            if (item.f_userinfo_id == this.checkrows[i].f_userinfo_id) {
              this.checkrows.splice(i, 1)
            }
          }
        }
      },
      ToshowModal() {
        this.creatPlanWay = 'single'
        if (this.checkrows.length > 0) {
          this.showModal = true
        } else {
          this.$showMessage("请选择需要安检的用户!")
        }
      },
      FiltrationPlan(){
        if(this.model.rows.length == 0){
          this.$showMessage("暂无可生成的计划！")
          return
        }
        this.creatPlanWay = 'filtration'
        this.showModal = true
      },
      AllPlan() {
        if(this.model.rows.length == 0){
          this.$showMessage("暂无可生成的计划！")
          return
        }
        this.creatPlanWay = 'all'
        this.showModal = true
      },
      cancel() {
        this.showModal = false
      },
      areas() {
        let rs = []
        for (let i = 0; i < this.$login.f.f_allArea.length; i++) {
          let temp = {
            label: this.$login.f.f_allArea[i].label,
            value: this.$login.f.f_allArea[i].label
          }
          rs.push(temp)
        }
        return [{label: '全部', value: ''}, ...rs]
      },
      initAdjustables() {
        console.log('初始化调压箱', this.$GetSaleParam)
        let arr = []
        let filter = this.$login.f.f_orgids
        this.$GetSaleParam.getAdjustable(filter).forEach((item) => {
          let temp = {}
          temp.label = `[${item.value.f_adjustable_id}]-${item.label}`
          temp.value = `${item.value.id}`
          arr.push(temp)
        })
        this.adjustables = [{label: '全部', value: ''}, ...arr]
      },
    },

    watch: {
      'model.f_usertype'(val){
        if(val == '民用'){
          this.model.safeCycle = this.civil
        }else if(val == '非民用'){
          this.model.safeCycle = this.civilian
        }
      },
      'model.SafeCheckXZ'(val) {
        this.model.SafeCheckSC = ''
        if (val == '已安检') {
          this.model.SafeCheckCQ = ''
          this.model.SafeCheckSX = {
            f_check_end: '', // 安检时间  查询起始条件
            f_check_start: ''// 安检时间  查询终止条件
          }
        } else {
          // 当使用筛选条件时，清空不需要的条件选项
          this.model.f_issue_start = ''
          this.model.f_issue_end = ''
          this.$refs.paged.$refs.criteria.model.f_check_start = ''
          this.$refs.paged.$refs.criteria.model.f_check_end = ''
          this.$refs.paged.$refs.criteria.model.f_last_check_state = ''
          this.model.month = ''
          if(val == '应安检'){
            this.model.SafeCheckSC = '否'

            this.model.f_issue_start = Util.toStartDateString()
            this.model.f_issue_end = Util.toStandardDateString()
          }
          // this.model.f_checktime_start = ''
          // this.model.f_checktime_end = ''
        }
      },
      'model.SafeCheckSC'(val) {
        if (val == '') {
          this.model.f_issue_start = ''
          this.model.f_issue_end = ''
        }
      },
      // 'checker'(val){
      //   console.log("checker",this.checker)
      //   if(val){
      //     this.checkboxModel.f_checker = this.checker[0].name
      //     this.checkboxModel.f_checker_id = this.checker[0].id
      //   }
      // },
      'model.rows'() {
        // if (!this.checkedAll) {//实现反选/
        // this.checkrows = [];
        for (let i = 0; i < this.$refs.paged.model.rows.length; i++) {
          var k = false
          for (let j = 0; j < this.checkrows.length; j++) {
            if (this.$refs.paged.model.rows[i].f_userinfo_id == this.checkrows[j].f_userinfo_id) {
              this.$set('$refs.paged.model.rows[' + i + '].checked', true)
              k = true
              continue
            }
          }
          if (!k) {
            this.$set('$refs.paged.model.rows[' + i + '].checked', false)
          }
        }
        // } else {//实现全选
        //   // this.checkboxModel = {};
        //   for (let i = 0; i < this.$refs.paged.model.rows.length; i++) {
        //     this.$set('$refs.paged.model.rows[' + i + '].checked', true)
        //   }
        // }
      }
    },
    computed: {
      selected() {
        return this.$refs.paged.$refs.grid.selected
      }
    }
  }
</script>
<style scoped>
  .newcolor{
    color:red;
  }
  .table th{
    background-color: #f2f6fa;
    color: black;
  }
</style>
