import {SearchList, date} from 'vue-client'
import {PagedList} from 'vue-client'
import {HttpResetClass,trans} from 'vue-client'
import Vue from "vue"
import co from 'co'
// let asyncReady = async function(self) {
//   // 获取配置信息
//   try {
//     // 获取配置文件
//     let http = new HttpResetClass()
//     let res  = await http.load('GET', `/phone/rs/vue`, {}, {resolveMsg: null, rejectMsg: null})
//     this.needconfig = res.data
//   } catch (error) {
//     // 忽略704,文件找不到异常R
//     if (error.status !== 704) {
//       throw error
//     }
//   }
// }
export default class Comp {

  /*async constructor() {
    await this.reaydy()
  }*/
  needconfig= {}
  isSend=true
  // 用户安检信息列表
  user = new SearchList(true)
  //遍历的按钮
  listbutton=[]
  fdevices=[]
  // 安检计划列表
  checkplan = new SearchList(true)
  // 安检计划的安检单列表
  checkplanitems = new SearchList(true)
  //按钮隐藏判断
  suppplanitem={}
  orderList= ['按时间降序', '按时间升序']//排序下拉框的值
  currentorder='按时间降序'//排序下拉框当前选中的值
  // 新增安检计划时保存的数据
  newPlan = {f_issued:"否",f_safecheck_type:"年度普检"}
  http = new HttpResetClass()
  //查询计划弹框中是否共享选项
  isAndNot = ["是", "否"]
  //用户类型
  userTypes = ["民用"]

  //安检计划查询中的是否是共享计划单选的当前选中值
  sIsAndNotSelect=''
  //用户列表的自选查询条件的值
  userCondition=["请选择条件","用户类型","地址"]
  //当前选中的下拉值
  userConditionSelect="请选择条件"
  //当前输入的值
  userConditionValue=""
  //计划项列表自选查询条件的值
  planItemCondition=["请选择条件","用户编号","用户名称"]
  //
  planItemConditional={}
  //入户状态
  userState=["到访不遇","拒检","入户"]
  //燃气使用
  gasUse=["已使用","未使用"]
  //当前选中的下拉值
  planItemConditionSelect="请选择条件"
  //当前输入的值
  planItemConditionValue=""
  //excel导入组件显示控制
  showModel=false
  //safecheckTypeList=Vue.$appdata.getParam("安检类型")
  safecheckTypeList=["年度普检"]
//安检员列表
  checker=[

  ]
  //公司安检员列表
  orgChecker=[]
  residential_area=[]
  checkersname=[]
  //新建计划时保存是否共享计划的值，
  isShare="否"
  //安检类型
  safecheckList=["年度普检"]
  //今年是否安检
  yearChecked=["全部","已检","未检"]
  yChecked=''
  //时间单位
  unitTime=["天","月"]
  selectTime="天"
  startday=""
  endday=""
  str=[]
  uploadCondition=''
//当前打开的安检计划id
  SelectedPlan={}
  //燃气表增添项
  gasexpress=[{"lname":"燃气表照片","type":"picture"},
    {"lname":"表品牌","type":"string","readonly":true},
    {"lname":"表号","type":"string","readonly":true},
    {"lname":"表封号","type":"number","readonly":true},
    {"lname":"表型号","type":"string","readonly":true},
    {"lname":"位置","type":"string","readonly":true},
    {"lname":"表底数","type":"number","readonly":true},
    {"lname":"左右表","type":"string","readonly":true}]
  //当前分公司id
  filialeid=global.login.orgid
  filialeidname=global.login.orgs
  orgs=[]
  //filialeid=20284

  usertypes=[]//用户类型
  metertypes=[]//气表分类
  pricetypes=[]//气价类型
  pricenames=["22222","222221"]//气价名称---遍历获取
  meterbrands= []//气表品牌---遍历获取
  gasproperties=[]//用气性质
  tablestate=[]//气表状态
  //用户列表查询条件json
  conditionJson=[
    {column:"f_building",checkname:"楼栋号码",type:"input"},
    {column:"useraddress",checkname:"地址",type:"input"},
    {column:"f_unit",checkname:"单元号码",type:"input"},
    {column:"userType",checkname:"用户类型",type:"selector",options:['民用','非民用','煤改气']},
    {column:"f_user_state",checkname:"用户状态",type:"selector",options:['正常','停用']},
    {column:"f_devices",checkname:"设备名称",type:"selector",options:['壁挂炉','热水器']},
    {column:"f_gasproperties",checkname:"用气性质",type:"selector",options:this.gasproperties},
    {column:"f_meter_classify",checkname:"气表分类",type:"selector",options:this.metertypes},
    {column:"f_table_state",checkname:"气表状态",type:"selector",options:this.tablestate},
    {column:"f_meter_brand",checkname:"气表品牌",type:"selector",options:this.meterbrands},
    {column:"f_price_type",checkname:"气价类型",type:"selector",options:this.pricetypes},
    {column:"f_price_name",checkname:"气价名称",type:"selector",options:this.pricenames}
  ]

  conditionList=[
    {selectitem:{column:"f_user_state",checkname:"用户状态",type:"selector",options:['正常','停用']},selectValue:'正常',num:0},
    {selectitem:{column:"useraddress",checkname:"地址",type:"input"},selectValue:'',num:1},
    {selectitem:{column:"userType",checkname:"用户类型",type:"selector",options:['民用','非民用','煤改气']},selectValue:'',num:2},
    {selectitem:{column:"f_gasproperties",checkname:"用气性质",type:"selector",options:this.gasproperties},selectValue:'',num:3},
    {selectitem:{column:"f_price_type",checkname:"气价类型",type:"selector",options:this.pricetypes},selectValue:'',num:4},
    {selectitem:{column:"f_price_name",checkname:"气价名称",type:"selector",options:this.pricenames},selectValue:'',num:5},
    {selectitem:{column:"f_meter_classify",checkname:"气表分类",type:"selector",options:this.metertypes},selectValue:'',num:6},
    {selectitem:{column:"f_meter_brand",checkname:"气表品牌",type:"selector",options:this.meterbrands},selectValue:'',num:7},
    {selectitem:{column:"f_table_state",checkname:"气表状态",type:"selector",options:this.tablestate},selectValue:'',num:8},
    {selectitem:{checkname:"请选择",type:"input"},selectValue:'',num:9}
  ]
  //安检项列表查询条件
  planitemconditionJson=[
    {column:"f_last_check_state",checkname:"安检结果",type:"selector",options:['入户','拒检','到访不遇','未使用']},
    {column:"f_start_time",checkname:"开始时间",type:"date"},
    {column:"f_end_time",checkname:"结束时间",type:"date"},
    {column:"f_last_check_result",checkname:"隐患状态",type:"selector",options:['正常','有隐患']},
    {column:"f_state1",checkname:"安检状态",type:"selector",options:['已检','未检']},
    {column:"f_area",checkname:"小区名称",type:"input"},
  ]
  planitemconditionList=[
    {selectitem:{column:"f_state1",checkname:"安检状态",type:"selector",options:['已检','未检']},selectValue:'',num:0},
    {selectitem:{column:"f_area",checkname:"小区名称",type:"input"},selectValue:'',num:1},
    {selectitem:{checkname:"请选择",type:"input"},selectValue:'',num:2}
  ]
  //所有小区
  areaList=[]
  //存放小区模糊查询数据
  areaText=''
  //营收参数
  saleParam=[]
  //存放

  SearchAreaList(f){
    let arr=['全部']
    this.areaList.forEach((area)=>{
      if(area.f_residential_area.indexOf(this.areaText)!=-1){
        console.log("area.f_residential_area:"+area.f_residential_area)
        arr.push(area.f_residential_area)
      }
    })
    this.residential_area=arr
    f()
  }

  //下拉框条件改变json数组
  conditionListChange(modelname,ind,key,value,f){
    console.log("------------"+ind+"-------------"+value)
    this[modelname][ind]["num"]=ind
    this[modelname][ind][key]=value
    f()
  }
  //条件改变时修改下级选项框值
  conditionChangeFun(type,f){
    console.log("开始刷新条件"+type)
    if(type=='userType' || type=='f_gasproperties' || type=='f_price_type' ){
      let usertype=''
      let gastype=''
      let pricetype=''
      let idx=9999
      this.conditionList.forEach((res)=>{
        if(res.selectitem.checkname=='用户类型'){
          usertype=res.selectValue
        }else if(res.selectitem.checkname=='用气性质'){
          gastype=res.selectValue
        }else if(res.selectitem.checkname=='气价类型'){
          pricetype=res.selectValue
        }
        if(res.selectitem.checkname=='气价名称'){
          idx=res.num
          this.conditionList[idx].selectitem.options=[]
        }
      })

      console.log("三个值："+usertype+"---"+gastype+"---"+pricetype)
      if(usertype && gastype && pricetype){
        console.log("加载气价名称列表")
        let arr=[]
        this.saleParam.price.forEach((pri)=>{
          if(pri.f_user_type==usertype && pri.f_price_type==pricetype && pri.f_gasproperties==gastype && pri.f_state=='有效'){
            this.pricenames.push(pri.f_price_name)
            if(idx!=9999){
              this.conditionList[idx].selectitem.options.push(pri.f_price_name)
            }
          }
        })
      }else{
        this.pricenames=[]
      }
      this.conditionJson[10].options=this.pricenames
      console.log("气价名称："+this.pricenames)
      f()
    }
  }
  formatArrayFun(type,arr){
    arr.forEach((result)=>{
      this[type].push(result.value)
    })
  }
//添加选择条件下拉框事件
  addconditionList(field,f){
    this[field].push({selectitem:{checkname:"请选择",type:"input"},selectValue:'',num:this.conditionList.length})
    f()
  }
//删除选择条件下拉框事件
  deletecondition(field,modelname,index,f){
    //如果有这个属性，说明已经选择过，去清空条件数组里的值
    if(this[field][index].selectitem.column){
      this.setProperty(modelname,this[field][index].selectitem.column,"")
    }
    this[field].splice(index,1)

    for (let i =0 ;i<this[field].length;i++){
      this.conditionList[i].num=i
    }
    f()
  }
  async ready() {
    // 加载所有安检计划
    //this.readConfig()
    if(!this.filialeid){
      Vue.showMessage("未检测到分公司信息，请重新登陆！")
      return
    }
    await this.getOrgs()
    this.checkplan.search.setField("safechecktype",'年度普检')
    await this.checkplan.searchList("/api/af-safecheck/sql/预约计划下发TS", {"f_plan_name": "f_plan_name like '%{}%'",
      "f_plan_year":"f_plan_year={}",
      "f_plan_month":"f_plan_month={}",
      "checkerid":"f_checker_id='{}'",
      "isAndNot":"f_checker {}",
      "safechecktype":"f_safecheck_type='{}'"
    },{groupitem:"",f_filialeids:"("+this.filialeid+")",orderitem:"f_create_time desc"})
    this.user.search.setField("f_filialeid",this.filialeid)
    this.setProperty('user', 'userType', '民用')
    //获取营收表具气价参数值
    new HttpResetClass().load('POST', '/api/af-safecheck/logic/getSaleInitData', {data:{
        f_orgid: `${this.filialeid}`
      }}, {resolveMsg: null, rejectMsg: null}).then((res)=>{
      console.log("--------:"+JSON.stringify(res))
      this.saleParam=res.data
      if(this.saleParam.gasbrands.length>0){
        this.saleParam.gasbrands.forEach((r)=>{
          this.meterbrands.push(r.f_meter_brand)
        })
      }
    })
    console.log(this.conditionList[3].selectitem.options)
    this.metertypes = this.formatArrayFun('metertypes',Vue.$appdata.getParam('气表类型'))
    this.pricetypes = this.formatArrayFun('pricetypes',Vue.$appdata.getParam('气价类型'))
    this.gasproperties = this.formatArrayFun('gasproperties',Vue.$appdata.getParam('用气性质'))
    this.tablestate = this.formatArrayFun('tablestate',Vue.$appdata.getParam('气表状态'))
    console.log(this.conditionList[3].selectitem.options)
    //this.getGasMan()
    await this.getAreaList()
    //加载安检员名单
    console.log("-----------------")
    console.log(Vue.$appdata)
    console.log("当前加载到的信息："+JSON.stringify(global.login))
    this.searchChecker(global.login.id)
  }

  show1(){
    this.showModel=true
  }
  //补录功能组装数据
  zzsj(){
    let deviceconfig=ObjConfig.getObjConfig(this.needconfig.safecheck.DevicesConfig)
    console.log("=============ZZSJ1>"+JSON.stringify(deviceconfig))
    for (let i = 0; i < deviceconfig.length; i++) {
      console.log("==============>"+JSON.stringify(deviceconfig[i]))
      console.log("==============>"+JSON.stringify(deviceconfig[i].index))
      this.str[deviceconfig[i].index-1]=deviceconfig[i]
      console.log("===========ZZSJ2>"+JSON.stringify(this.str[deviceconfig[i].index]))
    }

  }
  readConfig () {
    http.load('GET', `/phone/rs/vue`, {}, {resolveMsg: null, rejectMsg: null}).then(res => {
      this.needconfig = res.data
      // console.log(JSON.stringify(this.needconfig))
      // console.log("这是str1")
      //console.log(this.needconfig.safecheck.DevicesConfig)
      //console.log(JSON.stringify(this.needconfig.safecheck.DevicesConfig))
      let aa=this.needconfig.safecheck.DevicesConfig
      let bb= ObjConfig.getObjConfig(this.needconfig.safecheck.DevicesConfig)
      console.log("这是str2")
      console.log(JSON.stringify(bb))
      this.zzsj()
    })

  }
  //分公司发生改变
  async orgChange(value,f){
    console.log("----orgChange"+JSON.stringify(value))
    if(value.value==this.filialeid){
      f()
      return
    }
    this.filialeid=value.value
    this.filialeidname=value.label
    this.user = new SearchList(true)
    this.checkplanitems = new SearchList(true)
    this.checkplan = new SearchList(true)
    this.searchChecker(global.login.id)
    this.getAreaList()
    this.checkplan.search.setField("safechecktype",'年度普检')
    await this.checkplan.searchList("/api/af-safecheck/sql/预约计划下发TS", {"f_plan_name": "f_plan_name like '%{}%'",
      "f_plan_year":"f_plan_year={}",
      "f_plan_month":"f_plan_month={}",
      "checkerid":"f_checker_id='{}'",
      "isAndNot":"f_checker {}",
      "safechecktype":"f_safecheck_type='{}'"
    },{groupitem:"",f_filialeids:"("+this.filialeid+")",orderitem:"f_create_time desc"})
    this.user.search.setField("f_filialeid",this.filialeid)
    this.setProperty('user', 'userType', '民用')
    f()
  }
  //当前页面属性发生改变事件
  fieldChange(modelname,value,f){
    console.log(value)
    if(modelname=="user" || modelname=="checkplan" || modelname=="checkplanitems"){
      for(let i=0;i<this.orgChecker.length;i++){
        if(this.orgChecker[i].name==value){
          this.setProperty(modelname,"checkername",this.orgChecker[i].name)
          this.setProperty(modelname,"checkerid",this.orgChecker[i].id)
          break
        }
      }
      f()
      return
    }
    if(modelname=="createPlan"){
      for(let i=0;i<this.orgChecker.length;i++){
        if(this.orgChecker[i].name==value){
          this.newPlan.f_checker_id=this.orgChecker[i].id
          this.newPlan.f_checker=this.orgChecker[i].name
          break
        }
      }
      console.log("查询到的安检员详细信息："+JSON.stringify(this.newPlan))
      f()
      return
    }
    if(modelname=="upPlan"){
      for(let i=0;i<this.orgChecker.length;i++){
        if(this.orgChecker[i].name==value){
          this.plan.f_checker= this.orgChecker[i].name
          this.plan.f_checker_id=this.orgChecker[i].id
          break
        }
      }
      f()
      return
    }
    this[modelname]=value
    f()
  }

  jointCondition1(field,modelname){
    for (let i =0 ;i<this[field].length;i++){
      if(!this[field][i].selectValue){
        continue
      }
      console.log("this[field][i].column:"+this[field][i].column+"---"+"this[field][i].selectValue"+this[field][i].selectValue)
      this.setProperty(modelname,this[field][i].selectitem.column,this[field][i].selectValue)
    }
  }
  //根据选择框内容设置属性值
  jointCondition(modelname){

    if(modelname="user"){
      this.setProperty("user","usertype","")
      this.setProperty("user","address","")
      switch(this.userConditionSelect){
        case "用户类型":
          this.setProperty("user","usertype",this.userConditionValue)
          break;
        case "地址":
          this.setProperty("user","address",this.userConditionValue)
          break;
      }
    }
    if(modelname="checkplanitems"){
      this.setProperty("checkplanitems","usercode","")
      this.setProperty("checkplanitems","username","")
      switch(this.planItemConditionSelect){
        case "用户编号":
          this.setProperty("checkplanitems","usercode",this.planItemConditionValue)
          break;
        case "用户名称":
          this.setProperty("checkplanitems","username",this.planItemConditionValue)
          break;
      }
    }
  }

  //是否共享计划单选按钮事件
  isAndNotChange(isAndNotselect){
    this.sIsAndNotSelect=isAndNotselect
    if(this.sIsAndNotSelect=="是"){
      this.setProperty("checkplan","isAndNot","is null")
    }
    if(this.sIsAndNotSelect=="否"){
      this.setProperty("checkplan","isAndNot","is not null")
    }
  }

  //按条件查询所有安检计划
  async loadCheckPlan(sortfield,f) {
    this.isSend=true
    this.checkplan.check.checkes=[]
    if(sortfield){//如果传入空串说明是查询      传入非空串就是排序
      console.log("进入排序")
      if(sortfield==this.currentorder){
        return
      }else{
        this.currentorder=sortfield
      }
    }
    let fieldValue=''
    switch(this.currentorder){
      case "按时间降序":
        fieldValue='f_create_time desc'
        break
      case "按时间升序":
        fieldValue='f_create_time'
        break
    }
    console.log("值"+sortfield+"--当前值"+this.currentorder+"---排序值："+fieldValue)
    await this.checkplan.searchList("/api/af-safecheck/sql/预约计划下发TS",
      {"f_plan_name": "f_plan_name like '%{}%'",
        "f_plan_year":"f_plan_year={}",
        "f_plan_month":"f_plan_month={}",
        "checkerid":"f_checker_id='{}'",
        "isAndNot":"f_checker {}",
        "safechecktype":"f_safecheck_type='{}'"
      },
      {orderitem:fieldValue,
        f_filialeids:"("+this.filialeid+")",
        groupitem:""
      }
    )
    this.checkplan.check.checkAll=false
    this.checkplan.check.checkes=[]
    f()
    this.isSend=false
  }

  // 查询待检用户
  async searchUser(f) {
    this.isSend=true
    this.user.check.checkAll=false
    this.user.check.checkes=[]
    this.jointCondition1("conditionList","user")
    let sday=''
    let eday=''
    if(this.startday.trim()!=''){
      if(isNaN(this.startday) || isNaN(this.endday)){
        Vue.showMessage("请输入数字！")
        return
      }
      if(this.selectTime=="月"){
        sday= this.startday*30
        this.endday.trim()!=''?eday= this.endday*30:eday=''
      }else{
        sday= this.startday
        this.endday.trim()!=''?eday= this.endday:eday=''
      }
      if(eday){
        this.setProperty("user","checkTime"," DATEDIFF(dd,isnull(ua.f_last_check_date,ui.f_createfile_date),GETDATE())>="+parseInt(sday,10)+" and DATEDIFF(dd,isnull(ua.f_last_check_date,ui.f_createfile_date),GETDATE())<="+parseInt(eday,10))
      }else{
        this.setProperty("user","checkTime"," DATEDIFF(dd,isnull(ua.f_last_check_date,ui.f_createfile_date),GETDATE())>="+parseInt(sday,10))
      }

    }else{
      this.setProperty("user","checkTime","")
    }
    if(this.yChecked=='已检'){
      this.setProperty("user","ychecked","DateName(year,isnull(ua.f_last_check_date,'1990-01-01'))='"+new Date().getFullYear()+"'")
    }else if(this.yChecked=='未检'){
      this.setProperty("user","ychecked","DateName(year,isnull(ua.f_last_check_date,'1990-01-01'))!='"+new Date().getFullYear()+"'")
    }else{
      this.setProperty("user","ychecked","")
    }

    //this.user.search.setField("f_year_plan","<>")
    await this.user.searchList("/api/af-safecheck/sql/FetchUserFileByOrgNoRuHuSXQTS", {
      "f_filialeid": "ui.f_filialeid={}",
      "userinfocode": "ui.f_userinfo_code='{}'",
      "username": "ui.f_user_name like '%{}%'",
      "useraddress": "ua.f_address like '%{}%'",
      "userType":"uf.f_user_type='{}'",
      "f_residential_area":"ua.f_residential_area = '{}'",
      "f_building":"ua.f_building='{}'",
      "f_unit":"ua.f_unit='{}'",
      "f_user_state":"ui.f_user_state='{}'",
      "checkTime":"{}",
      "uploadCondition":"{}",
      "f_devices":"de.f_devices_type='{}'",
      "f_gasproperties":"sp.f_gasproperties='{}'",
      "f_meter_classify":"uf.f_meter_classify='{}'",
      "f_table_state":"uf.f_table_state='{}'",
      "f_meter_brand":"gb.f_meter_brand='{}'",
      "f_price_type":"sp.f_price_type='{}'",
      "f_price_name":"sp.f_price_name='{}'",
      "ychecked":" {}"
    }, {
      "orderitem": 'f_residential_area,f_building,f_unit,f_floor,f_room',
      "f_usertype": '',
      "month": '',
      "SafeCheckSX": {"f_check_start": '', "f_check_end": ''},
      "SafeCheckCQ": '',
      "startday":"",
      "f_plan_year":new Date().getFullYear()
    })
    f()
    this.isSend=false
  }

//限制用户购气
  LimitBuyGas(){

  }

  planIsChecked(issude,count) {
    if (issude == '未下发') {
      return true
    }
    if(count == 0){
      return true
    }
    return false
  }
  //查询安检员
  /*  searchChecker(id){
      new HttpResetClass().load('POST', '/rs/search', {
        source:  'this.getParentByType($department$).getAllChildrens().where(row.getAttributes().get($state$)==$在职$).where(row.getAttributes().get($rolestr$).indexOf($安检员$) != -1))',
        userid: id
      }, {resolveMsg: null, rejectMsg: null}).then((res)=>{
       this.checker=res.data
       console.log("安检员列表---"+JSON.stringify(res)+"---id"+this.filialeid)
     })

    }*/

  //查询安检员selectChanged
  async searchChecker(id){
    let res=await this.http.load('POST', '/rs/search', {
      source: 'tool.getChildrenOfResName($安检员$)',
      userid: id
    }, {resolveMsg: null, rejectMsg: null})
    this.checker=[]
    this.orgChecker=[]
    res.data.forEach((resRow) => {
      if(resRow.orgid==this.filialeid){
        this.checker.push(resRow.name)
        this.orgChecker.push(resRow)
      }
    })
    console.log("安检员列表---"+JSON.stringify(res)+"---id"+this.filialeid)
  }

  async searchPlanItems(f) {
    await this.checkplanitems.searchList("/api/af-safecheck/sql/planItemTS", {"f_plan_id": "f_plan_id={}"}, {})
    f()
  }
  //得到更新数据
  async getPaper(id,f) {
    let res=await this.http.load("POST", "/rs/path/getUserinfomation", {
      data:{
        condition:"f_check_item_id='"+id+"'"
      }
    })


    this.suppplanitem=res.data[0]
    if (this.suppplanitem.f_check_type!=null) {
      this.suppplanitem["f_user_type"]=this.suppplanitem.f_check_type
    }
    this.fdevices=[]

    if(this.suppplanitem.f_devices.length!=0){

      for (let i = 0; i <this.str.length ; i++) {
        if (this.suppplanitem.f_devices[i]==undefined) {
          this.fdevices.push({
            f_device_type: this.str[i].checkname,
            f_items: []
            //id: this.suppplanitem.f_devices[i] == undefined ? "" : this.suppplanitem.f_devices[i].id
          })
        }else {
          this.fdevices.push({
            f_device_type: this.str[i].checkname,
            f_items: [],
            id:this.suppplanitem.f_devices[i].id
          })
        }
      }
    }else{for (let i = 0; i <this.str.length ; i++) {

      this.fdevices.push({f_device_type:this.str[i].checkname,f_items:[]})
    }}

    this.setFitemvalue()
    f()



  }

//补录时改变fdevice
  suppfdevice(){
    for (let i = 0; i <this.str.length ; i++) {
      this.fdevices.push({f_device_type:this.str[i].checkname,f_items:[]})
    }
  }


  // 打开安检计划，加载安检计划的所有安检单
  async openPlan(plan, f) {
    this.isSend=true
    this.checkplanitems.check.checkes=[]
    this.checkplanitems.check.checkAll=false
    this.SelectedPlan=plan
    this.plan=plan
    this.checkplanitems.search.setField("f_plan_id", plan.id)
    this.checkplanitems.search.setField("f_state", "作废")
    await this.checkplanitems.searchList("/api/af-safecheck/sql/planItemTS", {"f_plan_id": "i.f_plan_id='{}'","f_state": "i.f_state !='{}'"}, {})
    f()
    this.isSend=false
    //this.checkplanitems.search.model.f_plan_id
  }

  //根据条件查询某个安检计划下的安检单
  async searchPlanItem(f) {
    this.checkplanitems.check.checkes=[]
    this.checkplanitems.check.checkAll=false
    if(this.checkplanitems.search.model.f_plan_id){
      this.isSend=true
      console.log("进入加载安检计划项"+this.checkplanitems.search.model.f_plan_id)
      this.jointCondition1("planitemconditionList","checkplanitems")
      await this.checkplanitems.searchList("/api/af-safecheck/sql/planItemTS",
        {"f_plan_id": "i.f_plan_id='{}'",
          "usercode": "i.f_userinfo_code='{}'",
          "username": "i.f_user_name='{}'",
          "f_address": "i.f_address like '%{}%'",
          "f_last_check_state": "i.f_last_check_state='{}' ",
          "f_start_time": "i.f_last_check_date >='{}'",
          "f_end_time": "i.f_last_check_date  <='{}'",
          "f_last_check_result":"i.f_last_check_result like '%{}%'",
          "f_state": "i.f_state !='{}'",
          "f_state1": "i.f_state ='{}'",
          "f_area":"i.f_residential_area='{}'"
        },
        {})
      f()
      this.isSend=false
    }else{
      Vue.showMessage("请选择安检计划")
    }
  }
//加载更多数据
  async loadMore(modelname,f) {
    this.isSend=true
    await this[modelname].list.loadMore()
    f()
    this.isSend=false
  }

  //点击全选按钮事件      user-用户列表       planitem-计划项列表
  changeCheckAll(modulename, f) {
    this[modulename].check.setCheckAll()
    f()
  }

  //当选中列表中某项时触发
  addParam(modulename, id) {
    console.log("当前值"+modulename+"--------"+id)
    this[modulename].check.setCheckes(id)
  }
  selectChanged(modulename, property, value,f){
    if(value=='全部'){
      this.setProperty(modulename, property, '')
    }else{
      this.setProperty(modulename, property, value)
    }
    f()
  }
  //设置属性值
  setProperty(modulename, property, value) {
    console.log(modulename+"新添--"+property+"--"+value)
    this[modulename].search.setField(property, value)
  }

  //列表中的选择框是否被选中
  hasValue(modulename,value){
    this[modulename].check.checks.has()
  }
  // 给新建安检计划设置属性值
  setNewPlan(property, value) {
    console.log(value)
    this.newPlan[property] = value
    return this
  }
  //将某项拖动到计划中
  //dragParam：从拖动的起始位置传入的参数
  async dragtoPlan(f_plan_id,f_safecheck_type,f_filialeid,dragParam,f){
    console.log("当前传入："+dragParam)
    await this.dragtoPlanItem(f_plan_id,f_safecheck_type,dragParam,f)
    await this.dragtoOtherPlanIteem(f_plan_id,dragParam,f)
  }

  //将客户信息拖至计划中
  async dragtoPlanItem(f_plan_id,f_safecheck_type,dragParam,f) {
    if (this.SelectedPlan.f_plan_year < new Date().getFullYear()) {
      return  Vue.showMessage("禁止给今年之前的计划添加新用户!")
    }
    let url=''
    console.log("计划id："+f_plan_id+"公司id："+this.filialeid)
    if(dragParam=='user'){
      if(!this.user.check.checkAll && this.user.check.checkes.length==0){
        Vue.showMessage("请选择用户后再进行添加！")
        return
      }
      this.jointCondition("user")
      if(this.user.search.model.userType){
        if(this.user.search.model.userType=='民用'){
          url="/api/af-safecheck/logic/AddCheckPlanItemTS"
        }else if(this.user.search.model.userType=='非民用'){
          url="/api/af-safecheck/logic/AddCheckPlanItemCivilTS"
        }else{
          Vue.showMessage("用户类型数据异常，请联系管理员！")
          return
        }
      }else{
        Vue.showMessage("请选择用户类型后！在进行计划下派操作")
        return
      }
      if(this.checkplanitems.search.model.f_plan_id){
        this.isSend=true
        let res=await this.http.load("POST", url, {
          data:{
            f_operator:global.login.name,
            f_plan_id:f_plan_id,
            f_safecheck_type:f_safecheck_type,
            f_filialeid:this.filialeid,
            f_subscribe_date:'',
            condition:this.user.search.search({
              "f_filialeid": "ui.f_filialeid={}",
              "userinfocode": "ui.f_userinfo_code='{}'",
              "username": "ui.f_user_name like '%{}%'",
              "useraddress": "ua.f_address like '%{}%'",
              "userType":"uf.f_user_type='{}'",
              "f_residential_area":"ua.f_residential_area = '{}'",
              "f_building":"ua.f_building='{}'",
              "f_unit":"ua.f_unit='{}'",
              "f_user_state":"ui.f_user_state='{}'",
              "checkTime":"{}",
              "uploadCondition":"{}",
              "f_devices":"de.f_devices_type='{}'",
              "f_gasproperties":"sp.f_gasproperties='{}'",
              "f_meter_classify":"uf.f_meter_classify='{}'",
              "f_table_state":"uf.f_table_state='{}'",
              "f_meter_brand":"gb.f_meter_brand='{}'",
              "f_price_type":"sp.f_price_type='{}'",
              "f_price_name":"sp.f_price_name='{}'",
              "ychecked":" {}"
            }),
            switchCheckAll:this.user.check.switchCheckAll,
            checkAll:this.user.check.checkAll,
            param:this.user.check.checkes,
            columnName: "ua.id",
            f_plan_year:new Date().getFullYear()
          }
        }, {resolveMsg: null, rejectMsg: null})
        console.log("重复数量-"+JSON.stringify(res.data.result)+"---"+res.data.result.length)
        if(res.data.code==200){
          //alert("添加成功！有"+res.data.result.length+"条用户地址已经存在于其他计划中:  \n"+res.data.result.reduce((c,v)=>{c += v.f_user_name+":"+v.f_address+"\n"}),0)
          Vue.showMessage("本次添加成功"+res.data.resultno[0].con+'户！'+(res.data.result.length>0?"另有"+res.data.result.length+"条用户地址已经存在于其他计划中":""))
        }else{
          if (res.data.msg) {
            Vue.showMessage(res.data.msg)
          } else {
            Vue.showMessage("添加失败！")
          }
        }
        this.user.check.checkes=[]
        await this.searchUser(()=>{})
        await this.searchPlanItem(()=>{})
        await this.loadCheckPlan("",()=>{})
        f()
        this.isSend=false
      }else{
        Vue.showMessage("请先打开一个计划再进行操作")
      }
    }
  }

  //将某个计划下的一项拖到另一个计划
  async dragtoOtherPlanIteem(checkplanid,dragParam,f) {

    /*if(dragParam=='item'){
      this.isSend=true
      let res=await this.http.load("POST", "/api/af-safecheck/logic/UpCheckPlanItem", {
        data:{
          f_operator:global.login.name,
          f_plan_id:checkplanid,
          condition:this.checkplanitems.search.search({"f_plan_id": "i.f_plan_id='{}'",
            "usercode": "i.f_userinfo_code='{}'",
            "username": "i.f_user_name='{}'",
            "f_address": "i.f_address like '%{}%'",
            "f_last_check_state": "i.f_last_check_state='{}' ",
            "f_start_time": "i.f_last_check_date >='{}'",
            "f_end_time": "i.f_last_check_date  <='{}'",
            "f_last_check_result":"i.f_last_check_result like '%{}%'",
            "f_state1": "i.f_state ='{}'",
            "f_state": "i.f_state !='{}'",
            "f_area":"i.f_residential_area='{}'"
          }),
          switchCheckAll:this.checkplanitems.check.switchCheckAll,
          checkAll:this.checkplanitems.check.checkAll,
          param:this.checkplanitems.check.checkes,
          columnName: "it.id"
        }
      }, {resolveMsg: null, rejectMsg: null})
      if(res.data.code==200){
        await this.searchUser(()=>{})
        await this.searchPlanItem(()=>{})
        await this.loadCheckPlan("",()=>{})
        f()
        Vue.showMessage("更换安检计划成功！")
      }else{
        Vue.showMessage("更换安检计划失败！")
      }
      f()
      this.isSend=false
    }*/

  }
  //清空用户编号
  clearUserInfoId(){
    this.setProperty("user","uploadCondition",'')
    Vue.showMessage("已清空用户编号")
  }
  //修改计划项状态为作废
  async delPlanItem(dragParam,f) {
    console.log("进入作废计划项方法")

    if(dragParam=='item'){
      if(this.SelectedPlan.f_issued=='已下发'
        && global.login.rolestr.indexOf("大区总经理")==-1
        && global.login.rolestr.indexOf("集团管理员")==-1
        && global.login.rolestr.indexOf("华东大区管理员")==-1
        && global.login.rolestr.indexOf("大区管理员")==-1
      ){
        Vue.showMessage("已下发计划无法删除用户！")
        return
      }
      this.isSend=true
      let resu=await this.http.load("POST", "/api/af-safecheck/logic/UpCheckPlanItemStateTS", {
        data: {
          f_operator:global.login.name,
          condition:this.checkplanitems.search.search({"f_plan_id": "i.f_plan_id='{}'",
            "usercode": "i.f_userinfo_code='{}'",
            "username": "i.f_user_name='{}'",
            "f_address": "i.f_address like '%{}%'",
            "f_last_check_state": "i.f_last_check_state='{}' ",
            "f_start_time": "i.f_last_check_date >='{}'",
            "f_end_time": "i.f_last_check_date  <='{}'",
            "f_last_check_result":"i.f_last_check_result like '%{}%'",
            "f_state": "i.f_state !='{}'",
            "f_state1": "i.f_state ='{}'",
            "f_area":"i.f_residential_area='{}'"
          }),
          switchCheckAll:this.checkplanitems.check.switchCheckAll,
          checkAll:this.checkplanitems.check.checkAll,
          param:this.checkplanitems.check.checkes,
          columnName: "i.id"
        }
      }, {resolveMsg: null, rejectMsg: null})
      console.log("-----------"+JSON.stringify(resu.data))
      if(resu.data.code==200){
        Vue.showMessage("作废安检单成功! 成功作废:"+resu.data.res.up+"条"+(resu.data.res.noup>0?"有"+resu.data.res.noup+"条已经不是 ‘未检’ 状态！":""))
        await this.searchUser(()=>{})
        await this.searchPlanItem(()=>{})
        await this.loadCheckPlan("",()=>{})
        f()
      }else{
        Vue.showMessage("取消安检计划失败!")
      }
      this.isSend=false
    }

  }

  //新建计划
  async addNewPlan(f) {
    if(!this.validationCreatePlan()){
      return
    }
    this.isSend=true
    /*if(this.newPlan.f_safecheck_type=='散户安检'){
      let res=await this.http.load("POST","/api/af-safecheck/sql/getCheckplan", {data: {condition:`f_plan_year='${this.newPlan.f_plan_year}' and f_plan_month='${this.newPlan.f_plan_month}' and f_checker_id='${this.newPlan.f_checker_id}' and f_safecheck_type='${this.newPlan.f_safecheck_type}'`,sortfield:'f_create_time desc'}}, {resolveMsg: null, rejectMsg: null})
      console.log("结果-"+res.data.length)
      if(res.data.length>0){
        Vue.showMessage("当月已生成该安检员的散户计划，无法再次生成！")
        this.isSend=false
        return
      }else{
        this.newPlan.f_plan_name=this.newPlan.f_plan_year+"年"+this.newPlan.f_plan_month+"月散户计划"
      }
    }*/

    if(this.isShare=="是"){
      this.newPlan.f_checker_id=null
      this.newPlan.f_checker=null
    }
    let d1=new Date()
    this.newPlan.f_plan_name=d1.getFullYear()+'年'+(d1.getMonth()+1)+'月'+this.newPlan.f_plan_name+'年度普检计划'
    this.newPlan.f_plan_type='预约计划'
    this.newPlan.f_subcompany=global.login.orgs
    this.newPlan.f_filialeid=this.filialeid
    this.newPlan.f_create_operator=global.login.name
    this.newPlan.f_create_time=this.getNowFormatDate()
    await Vue.resetpost("/api/af-safecheck/logic/createCheckPlanTS", {"data": this.newPlan},{resolveMsg : '新建计划成功！', rejectMsg : '新建计划失败！'},2500)
    await this.loadCheckPlan('',()=>{})
    this.newPlan={f_issued:"否",f_safecheck_type:"年度普检"}
    this.isShare="否"
    f()
    window.dispatchEvent(new CustomEvent("goRefresh"),{})
    this.isSend=false
  }

  // 取消新建安检计划
  cancel() {
    this.newPlan={f_issued:"否",f_safecheck_type:"年度普检"}
    this.isShare="否"
    this.plan={}
  }

  //获取安检计划中已办数量，除去所有未办的，都算已办
  /*getChecked(plan) {
    //console.log("加载已办数量"+JSON.stringify(plan))
    return this.sum(plan.f_items,'f_state', 'num', ['已检', '作废'])
  }

  //获取安检计划未检数量
  getNotChecked(plan) {
    //console.log("加载未检数量"+JSON.stringify(plan))
    return this.sum(plan.f_items,'f_state', 'num', ['未检'])
  }

  // 获取总数
  getSumItem(plan) {
    //console.log("加载总数量"+JSON.stringify(plan))
    return this.sum(plan.f_items,'f_state', 'num', ['未检', '已检', '作废'])
  }

  sum(arr,keyName, sumName, keys) {
    return arr.reduce(function(prev, curr, idx, arr){
      // 如果求和主键包括当前主键，进行累加，否则，不累加
      if (keys.find(function(v) {
        return v === curr[keyName]
      })) {
        return prev + curr[sumName];
      } else {
        return prev
      }
    }, 0)
  }*/
  // 取年的选择项目
  years() {
    return date.yearSelects
  }
  /*
   1.获取配置文件
   2.组装配置文件  （配置文件[]    JS提前固定的数组[]  return []）
    */

  // str = [
  //   {
  //     "checkname": "燃气表",
  //     "checkmust":false,
  //     "items":[
  //       {"lname": "表具状态","multiple":false,"type":"selector","options":[{"data":"正常","isdefect":false,"isdefault": true},{"data":"包裹","isdefect":true,"level":"C2","isdefault": false,"tooltip":"1.整改时限1日，2，禁止使用，及时联系公司客服"},{"data":"漏气","isdefect":true,"level":"A1","isdefault": false,"tooltip":"1.整改时限1日，2，禁止使用，及时联系公司客服"}]},
  //       {"lname": "表故障","multiple":true,"type":"selector","options":[{"data":"正常","isdefect":false,"isdefault": true},{"data":"破损变形","isdefect":true,"level":"B2","isdefault": false,"tooltip":"1.整改时限1日，2，禁止使用，及时联系公司客服"},{"data":"失效","isdefect":true,"level":"B2","isdefault": false},{"data":"不走字","isdefect":true,"level":"B2","isdefault": false},{"data":"铅封损坏","isdefect":true,"level":"B2","isdefault": false},{"data":"气表到期(使用年限超过八年)","isdefect":true,"level":"B2","isdefault": false}]},
  //       {"lname": "腐蚀","multiple":false,"type":"selector","options":[{"data":"正常","isdefect":false,"isdefault": true},{"data":"轻微","isdefect":false,"isdefault": false},{"data":"中度","isdefect":false,"isdefault": false},{"data":"严重","isdefect":true,"level":"A2","isdefault": false,"tooltip":"1.整改时限1日，2，禁止使用，及时联系公司客服"}]},
  //       {"lname": "使用年限","type":"string", "data": 8,"isshow": false}
  //     ]
  //   },
  //   {
  //     "checkname": "阀门",
  //     "checkmust":true,
  //     "items":[
  //       {"lname": "阀门","multiple":true,"type":"selector","options":[{"data":"无阀门","isdefect":true,"level":"A2"},{"data":"无阀柄","isdefect":true,"level":"A2"},{"data":"失效","isdefect":true,"level":"A2"}]},
  //       {"lname": "表前阀","multiple":false,"type":"selector","options":[{"data":"正常","isdefect":false,"isdefault": true},{"data":"异常","isdefect":true,"level":"A1","isdefault": false}]},
  //       {"lname": "灶前阀","multiple":false,"type":"selector","options":[{"data":"正常","isdefect":false,"isdefault": true},{"data":"异常","isdefect":true,"level":"A1","isdefault": false}]},
  //       {"lname":"使用年限","type":"string", "data": 8,"isshow": false}
  //     ]
  //   },
  //   {
  //     "checkname": "户内管",
  //     "quantity": 2,
  //     "checkmust":true,
  //     "items":[
  //       {"lname": "穿墙管","multiple":false,"type":"selector","options":[{"data":"正常","isdefect":false,"isdefault": true},{"data":"异常","isdefect":true,"level":"A8"}]},
  //       {"lname": "胶管","multiple":true,"type":"selector","options":[{"data":"正常","isdefect":false,"isdefault": true},{"data":"老化、超期使用","isdefect":true,"level":"A8"},{"data":"未紧箍","isdefect":true,"level":"C2"},
  //           {"data":"软管穿墙","isdefect":true,"level":"C2"},{"data":"软管超长（长度超过两米）","isdefect":true,"level":"C2"},{"data":"非专用软管","isdefect":true,"level":"C2"}]},
  //       {"lname": "镀锌管","multiple":false,"type":"selector","options":[{"data":"正常","isdefect":false,"isdefault": true},{"data":"异常","isdefect":true,"level":"A8"}]},
  //       {"lname": "铝塑管、波纹管","multiple":false,"type":"selector","options":[{"data":"正常","isdefect":false,"isdefault": true},{"data":"异常","isdefect":true,"level":"A8"}]},
  //       {"lname": "热水器管","multiple":false,"type":"selector","options":[{"data":"正常","isdefect":false,"isdefault": true},{"data":"异常","isdefect":true,"level":"A8"}]},
  //       {"lname":"使用年限","type":"string", "data": 8,"isshow": false}
  //     ]
  //   },
  //   {
  //     "checkname": "热水器",
  //     "quantity": 0,
  //     "checkmust":false,
  //     "items":[
  //       {"lname": "热水器品牌","type":"string"},
  //       {"lname": "热水器烟道","multiple":true,"type":"selector","options":[{"data":"正常","isdefect":false},{"data":"未安装烟道","isdefect":true,"level":"A8","tooltip":"1.整改时限1日，2，禁止使用，及时联系公司客服"},{"data":"烟道未与大气直接连通","isdefect":true,"level":"A8"},{"data":"安装不规范","isdefect":true,"level":"A8"}]},
  //       {"lname": "安装位置","multiple":false,"type":"selector","options":[{"data":"卫生间","isdefect":false},{"data":"卧室","isdefect":true,"level":"A8"},
  //           {"data":"客厅过道","isdefect":true,"level":"A8"},{"data":"内厨房","isdefect":true,"level":"A8"},{"data":"其他密封或通风不良房间","isdefect":true,"level":"A8"}]},
  //       {"lname": "工作状态","multiple":false,"type":"selector","options":[{"data":"正常","isdefect":false},{"data":"异常","isdefect":true,"level":"A8"}]},
  //       {"lname":"使用年限","type":"string", "data": 4,"isshow": false}
  //     ]
  //   },
  //   {
  //     "checkname": "燃气具",
  //     "checkmust":false,
  //     "items":[
  //       {"lname": "燃气具品牌","type":"string"},
  //       {"lname": "安装位置","multiple":false,"type":"selector","options":[{"data":"正常","isdefect":false,"isdefault": true},{"data":"异常","isdefect":true,"level":"A8","isdefault": false}]},
  //       {"lname": "安装状况","multiple":false,"type":"selector","options":[{"data":"正常","isdefect":false,"isdefault": true},{"data":"超年限（使用年限为8年）","isdefect":true,"level":"A8","isdefault": false}]},
  //       {"lname":"使用年限","multiple":false,"type":"string", "data": 4}
  //     ]
  //   },
  //   {
  //     "checkname": "其他",
  //     "checkmust":false,
  //     "items":[
  //       {"lname": "使用简易三通","multiple":false,"type":"selector","options":[{"data":"否","isdefect":false},{"data":"是","isdefect":true,"level":"A8"}]},
  //       {"lname": "私自安装、改迁燃气设施及设备","multiple":false,"type":"selector","options":[{"data":"否","isdefect":false},{"data":"是","isdefect":true,"level":"A8","tooltip":"1.整改时限1日，2，禁止使用，及时联系公司客服"}]},
  //       {"lname": "违反安全间距规定","multiple":false,"type":"selector","options":[{"data":"否","isdefect":false},{"data":"是","isdefect":true,"level":"A8"}]},
  //       {"lname": "燃气设施及设备上搭挂重物","multiple":false,"type":"selector","options":[{"data":"否","isdefect":false},{"data":"是","isdefect":true,"level":"A8"}]},
  //       {"lname": "燃气管道被作电器接地线使用","multiple":false,"type":"selector","options":[{"data":"否","isdefect":false},{"data":"是","isdefect":true,"level":"A8"}]}
  //     ]
  //   }
  // ]
  //str=[{"checkname":"热水器","index":3,"items":[{"lname":"烟道式安装在卫生间","multiple":false,"options":[{"isdefect":true,"data":"是","isdefault":false},{"isdefect":false,"data":"否","isdefault":true}],"index":1,"type":"selector"},{"lname":"已过八年强制报废期","multiple":false,"options":[{"isdefect":true,"data":"是","isdefault":false},{"isdefect":false,"data":"否","isdefault":true}],"index":4,"type":"selector"},{"lname":"热水器泄露","multiple":false,"options":[{"isdefect":true,"data":"是","isdefault":false},{"isdefect":false,"data":"否","isdefault":true}],"index":3,"type":"selector"},{"lname":"热水器品牌","index":5,"type":"string"},{"lname":"启用时间","index":6,"type":"date"},{"lname":"强制式安排在卫生间","multiple":false,"options":[{"isdefect":true,"data":"是","isdefault":false},{"isdefect":false,"data":"否","isdefault":true}],"index":2,"type":"selector"}]},{"checkname":"炉","index":2,"items":[{"lname":"嵌入式炉子下面柜门无通风口","multiple":false,"options":[{"isdefect":true,"data":"是","isdefault":false},{"isdefect":false,"data":"否","isdefault":true}],"index":4,"type":"selector"},{"lname":"炉泄露","multiple":false,"options":[{"isdefect":true,"data":"是","isdefault":false},{"isdefect":false,"data":"否","isdefault":true}],"index":1,"type":"selector"},{"lname":"已过8年强制报废期","multiple":false,"options":[{"isdefect":true,"data":"是","isdefault":false},{"isdefect":false,"data":"否","isdefault":true}],"index":2,"type":"selector"},{"lname":"炉子品牌","index":5,"type":"string"},{"lname":"无自动熄火保护装置","multiple":false,"options":[{"isdefect":true,"data":"是","isdefault":false},{"isdefect":false,"data":"否","isdefault":true}],"index":3,"type":"selector"},{"lname":"启用时间","index":6,"type":"date"}]},{"checkname":"灶前阀","index":4,"items":[{"lname":"无把柄","multiple":false,"options":[{"isdefect":true,"data":"是","isdefault":false},{"isdefect":false,"data":"否","isdefault":true}],"index":3,"type":"selector"},{"lname":"泄露","multiple":false,"options":[{"isdefect":true,"data":"是","isdefault":false},{"isdefect":false,"data":"否","isdefault":true}],"index":1,"type":"selector"},{"lname":"开关不便","multiple":false,"options":[{"isdefect":true,"data":"是","isdefault":false},{"isdefect":false,"data":"否","isdefault":true}],"index":2,"type":"selector"}]},{"checkname":"其他","index":7,"items":[{"lname":"其他/压力","index":1,"type":"string"}]},{"checkname":"胶管","index":5,"items":[{"lname":"超2年","multiple":false,"options":[{"isdefect":true,"data":"是","isdefault":false},{"isdefect":false,"data":"否","isdefault":true}],"index":2,"type":"selector"},{"lname":"超2米","multiple":false,"options":[{"isdefect":true,"data":"是","isdefault":false},{"isdefect":false,"data":"否","isdefault":true}],"index":4,"type":"selector"},{"lname":"穿墙","multiple":false,"options":[{"isdefect":true,"data":"是","isdefault":false},{"isdefect":false,"data":"否","isdefault":true}],"index":5,"type":"selector"},{"lname":"老化","multiple":false,"options":[{"isdefect":true,"data":"是","isdefault":false},{"isdefect":false,"data":"否","isdefault":true}],"index":1,"type":"selector"},{"lname":"无管卡","multiple":false,"options":[{"isdefect":true,"data":"是","isdefault":false},{"isdefect":false,"data":"否","isdefault":true}],"index":3,"type":"selector"}]},{"checkname":"管道","index":6,"items":[{"lname":"泄露","multiple":false,"options":[{"isdefect":true,"data":"是","isdefault":false},{"isdefect":false,"data":"否","isdefault":true}],"index":1,"type":"selector"},{"lname":"一般锈蚀","multiple":false,"options":[{"isdefect":true,"data":"是","isdefault":false},{"isdefect":false,"data":"否","isdefault":true}],"index":4,"type":"selector"},{"lname":"暗埋","multiple":false,"options":[{"isdefect":true,"data":"是","isdefault":false},{"isdefect":false,"data":"否","isdefault":true}],"index":2,"type":"selector"},{"lname":"严重锈蚀","multiple":false,"options":[{"isdefect":true,"data":"是","isdefault":false},{"isdefect":false,"data":"否","isdefault":true}],"index":3,"type":"selector"},{"lname":"悬挂物品","multiple":false,"options":[{"isdefect":true,"data":"是","isdefault":false},{"isdefect":false,"data":"否","isdefault":true}],"index":5,"type":"selector"}]},{"checkname":"燃气表","index":1,"items":[{"lname":"表前阀无把柄","multiple":false,"options":[{"isdefect":true,"data":"是","isdefault":false},{"isdefect":false,"data":"否","isdefault":true}],"index":16,"type":"selector"},{"lname":"运转正常","multiple":false,"options":[{"isdefect":false,"data":"是"},{"isdefect":false,"data":"否","isdefault":true}],"index":11,"type":"selector"},{"lname":"表不转动","multiple":false,"options":[{"isdefect":true,"data":"是","isdefault":false},{"isdefect":false,"data":"否","isdefault":true}],"index":12,"type":"selector"},{"lname":"表前阀泄露","multiple":false,"options":[{"isdefect":true,"data":"是","isdefault":false},{"isdefect":false,"data":"否","isdefault":true}],"index":15,"type":"selector"},{"lname":"表前阀开关不便","multiple":false,"options":[{"isdefect":true,"data":"是","isdefault":false},{"isdefect":false,"data":"否","isdefault":true}],"index":17,"type":"selector"},{"lname":"未封表","multiple":false,"options":[{"isdefect":true,"data":"是","isdefault":false},{"isdefect":false,"data":"否","isdefault":true}],"index":13,"type":"selector"},{"lname":"封闭无通风","multiple":false,"options":[{"isdefect":true,"data":"是","isdefault":false},{"isdefect":false,"data":"否","isdefault":true}],"index":14,"type":"selector"}]}]


  //遍历选择框以及得到list
  getselector(){
    this.listbutton=[]

    for (let i = 0; i <this.str.length ; i++) {
      let strlist=[]
      strlist=this.str[i].items.concat()
      for (let j = 0; j <strlist.length ; j++) {
        strlist[j]["mname"]=this.str[i].checkname
      }
      strlist.splice(0,0,{lname:this.str[i].checkname+":",type:"",mname:""})
      let bb=this.listbutton
      this.listbutton=bb.concat(strlist)


    }

    let h=this.listbutton
    for (let i = 0; i <h.length ; i++) {

      h[i]["selected"]=""
      h[i]["level"]=""
      h[i]["isdefect"]=""
      if (h[i].type =="selector"){
        let size=h[i].options.length

        let pl=[]
        for (let j = 0; j <size ; j++) {
          let n=h[i].lname+h[i].mname

          pl.push(h[i].options[j].data)
          this.planItemConditional[n]=pl

        }
      }
    }


  }
  //返回遍历的option
  reoption(key1,key2){

    let modelname=key1+key2
    return this.planItemConditional[modelname]

  }


  // 取月的选择项目
  months() {
    return date.monthSelects
  }

  //下发安检计划
  async sendCheckPlan(f){
    if(this.checkplan.check.checkes.length<1){
      Vue.showMessage("请选择要下发的安检计划")
      return
    }
    this.isSend=true
    let res=await this.http.load("POST", "/api/af-safecheck/logic/NewBespeakCheckPlanTS", {
      data:{
        f_issued:'是',
        f_issue_time:this.getNowFormatDate(),
        f_send_operator:global.login.name,
        param:this.checkplan.check.checkes,
      }
    }, {resolveMsg: null, rejectMsg: null})
    if(res.data.code==200){
      //Vue.showMessage("下发成功！其中有"+res.data.repet+"个计划己经是下发状态")
      Vue.showMessage("下发成功！")
      await  this.loadCheckPlan('',()=>{})
      f()
    }else{
      Vue.showMessage("下发失败！")
    }
    this.isSend=false
  }

  //删除安检计划
  async delCheckPlan(f){
    if(this.checkplan.check.checkes.length<1){
      Vue.showMessage("请选择要删除的安检计划")
      return
    }
    this.isSend=true
    let res=await this.http.load("POST", "/api/af-safecheck/logic/deleteCheckPlanTS", {
      data:{
        f_operator:global.login.name,//global.login.name,
        condition:this.checkplan.search.search({}),
        switchCheckAll:this.checkplan.check.switchCheckAll,
        checkAll:this.checkplan.check.checkAll,
        param:this.checkplan.check.checkes,
        columnName: "f_plan_id"
      }
    }, {resolveMsg: "删除成功！", rejectMsg: "删除失败！"})
    console.log(JSON.stringify(res))
    if(res.data.code==200){
      Vue.showAlert("删除成功！","success",2500)
      await  this.loadCheckPlan('',()=>{})
    }else{
      Vue.showAlert("删除失败！","success",2500)
    }
    this.checkplanitems.search.model.f_plan_id=""
    this.checkplanitems.list.data=[]
    f()
    this.isSend=false
  }
  //修改计划时 用来存储当前选中要修改的计划
  plan={}
  setPlanVal(value){
    console.log(value)
    this.plan=JSON.parse(JSON.stringify( value ))
  }
  setPlan(key,val){
    this.plan[key]=val
  }
  isUpdate(key1,key2){
    if (key1=="已检"&&key2!="补录"){
      return true;
    }
    return false;
  }
  //修改安检计划
  async upCheckPlan(f){
    if(this.plan.f_issued=='已下发'){
      Vue.showMessage("该计划已下发，无法进行修改！")
      return
    }
    this.isSend=true
    let res=await this.http.load("POST", "/api/af-safecheck/logic/updateCheckPlanTS", {
      data:{
        f_checker:this.plan.f_checker,
        f_checker_id:this.plan.f_checker_id,
        f_plan_name:this.plan.f_plan_name,
        f_plan_year:this.plan.f_plan_year,
        f_plan_month:this.plan.f_plan_month,
        f_plan_id:this.plan.id
      }
    }, {resolveMsg: null, rejectMsg: null})
    if(res.data.code==200){
      Vue.showAlert("修改成功！"+res.data.message,"success",2500)
      await  this.loadCheckPlan('',()=>{})
    }else{
      Vue.showAlert("修改失败！"+res.data.message,"success",2500)
    }
    f()
    window.dispatchEvent(new CustomEvent("goRefresh"),{})
    this.isSend=false
  }

  /*  getDataLength(modelname){
      console.log("sdadasdasdasdadasdadddddddddddddddddddddddddddddddddddddddddddd")
      let l=this[modelname].list.data.length
      console.log("--"+l)
      return l
    }*/
  //新建安检计划非空判断
  validationCreatePlan(){
    if(this.newPlan.f_safecheck_type!='散户安检'){
      if(!this.newPlan.f_plan_name){
        Vue.showMessage("请输入安检计划名称！")
        return false
      }
    }
    if(!this.newPlan.f_plan_year){
      Vue.showMessage("请选择安检年份！")
      return false
    }
    if(!this.newPlan.f_plan_month){
      Vue.showMessage("请选择安检月份！")
      return false
    }
    if(this.isShare=="否"){
      if(!this.newPlan.f_checker){
        Vue.showMessage("请选择安检人员！")
        return false
      }
    }else{
      this.newPlan.f_checker=''
    }
    if(!this.newPlan.f_safecheck_type){
      Vue.showMessage("请选择安检类型！")
      return false
    }

    return true
  }

//调用updatecheckpaper
  async addNewPaper(f){
    this.setFdevices()
    this.setfDevicesid()
    //return;
    for (var i = 0; i <this.checkerMess.length ; i++) {
      if (this.checkerMess[i].name==this.suppplanitem.f_checker_name){
        this.suppplanitem["f_checker_id"]=this.checkerMess[i].id
      }
    }
    //console.log(this.fdevices)
    //return;
    this.suppplanitem["f_devices"]=this.fdevices
    this.suppplanitem.f_check_type=this.suppplanitem.f_user_type
    this.suppplanitem.f_state = "已检"
    this.suppplanitem.f_approved = "未审核"
    this.suppplanitem.f_complete  = "已完成"
    this.suppplanitem.f_no_checkplan ="有计划安检"
    //return;
    this.suppplanitem.f_check_plan_id=this.suppplanitem.f_plan_id

    let res=await this.http.load("POST", "/api/af-safecheck/logic/SuppCheckPaper", {data:{paper:this.suppplanitem}})

    this.openPlan(this.plan,f)
    f()
  }
  addnewPaper(f){
    delete this.suppplanitem.id
    this.addNewPaper(f)
  }
  updatePaper(f){
    this.addNewPaper(f)
  }
  setNewPaper(property,value){
    this.suppplanitem[property] = value



    return this
  }

  setFdevices(){


    var ar=this.listbutton
    var br=this.fdevices
    for (var i = 0; i <br .length; i++) {
      for (var j = 0; j < ar.length; j++) {
        if (br[i].f_device_type == ar[j].mname) {
          br[i].f_items.push({
            f_item_name: ar[j].lname,
            f_item_value: ar[j].selected,
            type: ar[j].type,
            f_is_defect: ar[j].isdefect,
            f_defect_level: ar[j].level,
            f_item_lists:[{
              //f_item_id: "",
              f_item_value: ar[j].selected,
              //id:""
            }]
          })
        }
      }
    }
  }
  //给fdevices赋值id
  setfDevicesid(){
    var suppf=this.suppplanitem.f_devices
    var fde=this.fdevices
    if (this.suppplanitem.hasOwnProperty("f_devices")){
      for (let i = 0; i <suppf.length ; i++) {
        for (let j = 0; j <fde.length; j++) {
          if (suppf[i].f_device_type==fde[j].f_device_type){
            for (let k = 0; k <suppf[i].f_items.length ; k++) {
              // console.log("789456123")
              for (let l = 0; l <fde[j].f_items.length ; l++) {
                // console.log("11111111111111")
                if (suppf[i].f_items[k].f_item_name==fde[j].f_items[l].f_item_name) {
                  fde[j].f_items[l]["id"]=suppf[i].f_items[k].id
                  if (suppf[i].f_items[k].f_item_lists.length!=0){
                    fde[j].f_items[l].f_item_lists[0]["id"]=suppf[i].f_items[k].f_item_lists[0].id
                    fde[j].f_items[l].f_item_lists[0]["f_item_id"]=suppf[i].f_items[k].f_item_lists[0].f_item_id
                  }
                }
              }
            }
          }
        }
      }
    }else {
      this.suppplanitem.f_upload_date=this.getNowFormatDate()
    }
  }
  //
  setFitemvalue(){
    for (var k = 0; k <this.listbutton.length ; k++) {
      for (var i = 0; i <this.suppplanitem.f_devices.length ; i++) {
        for (var j = 0; j < this.suppplanitem.f_devices[i].f_items.length; j++) {
          if (this.listbutton[k].lname==this.suppplanitem.f_devices[i].f_items[j].f_item_name){
            this.listbutton[k].selected=this.suppplanitem.f_devices[i].f_items[j].f_item_value
          }
        }
      }
    }
  }
  //改变selected属性
  changeSelected(selectedname,selectedmname,selectedvalue){
    var sa=this.listbutton
    for (var i = 0; i <sa.length; i++) {
      if (sa[i].lname==selectedname&&sa[i].mname==selectedmname){
        sa[i].selected=selectedvalue
        if (sa[i].type=="selector"){//判断是否是选择类型
          for (var j = 0; j < sa[i].options.length; j++) {
            if (sa[i].options[j].data==selectedvalue){//赋值为json的level和isdefect
              sa[i].level=sa[i].options[j].level
              sa[i].isdefect=sa[i].options[j].isdefect
            }
          }
        }
      }
    }
//console.log(this.fdevices)
  }
  async getAreaList() {
    let res =await new HttpResetClass().load('POST', '/api/af-safecheck/logic/safe_singleTable_GroupBy', {
      data: {
        items: 'f_residential_area',
        tablename: 't_area',
        condition: 'f_filialeid = '+this.filialeid,
        groupitem: 'f_residential_area'
      }
    }, {resolveMsg: null, rejectMsg: null})
    if (res.data) {
      let arr=['全部']
      this.areaList=res.data
      for(let i =0 ;i<res.data.length;i++){
        arr.push(res.data[i].f_residential_area)
      }
      //this.conditionJson[0].options=arr
      this.residential_area=arr
    }

  }

//获取当前时间
  getNowFormatDate() {
    let date = new Date();
    let seperator1 = "-";
    let seperator2 = ":";
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    let hour = date.getHours();
    let min = date.getMinutes();
    let second = date.getSeconds();
    if (month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = "0" + strDate;
    }
    if (hour >= 0 && hour <= 9) {
      hour = "0" + hour;
    }
    if (min >= 0 && min <= 9) {
      min = "0" + min;
    }
    if (second >= 0 && second <= 9) {
      second = "0" + second;
    }
    let currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
      + " " + hour + seperator2 + min
      + seperator2 + second;
    return currentdate;
  }
//获取安检人员
  async getGasMan(){

    let http = new HttpResetClass()
    let getGasman = await http.load('POST', '/rs/search', {
      source: 'this.getParentByType($department$).getAllChildrens().where(row.getAttributes().get($rolestr$).indexOf($安检员$) != -1))',
      userid: global.login.id
    }, {resolveMsg: null, rejectMsg: null})

    this.checkerMess=getGasman.data
    for (var i = 0; i <getGasman.data.length ; i++) {
      this.checkersname.push(getGasman.data[i].name)
    }

  }
  async getOrgs(){
    let http = new HttpResetClass()
    let orgs = await http.load('POST', '/rs/search', {
      source: 'this.getParentByType($organization$).getAllChildrens().where(row.getType() == $organization$)',
      userid: global.login.id
      //userid:"15130"
    }, {resolveMsg: null, rejectMsg: '获取分公司出错！！！'})
    console.log("分公司--"+JSON.stringify(orgs))
    this.orgs = []
    if(orgs.data.length>0){
      orgs.data.forEach((res) => {
        this.orgs.push({label: res.name, value: res.id})
      })
    }else{
      this.orgs.push({label: this.filialeidname, value:this.filialeid})
      // this.orgs.push({label: '测试公司', value:222})
    }


  }

  //excel导出
  async exportFile(){
    if(this.user.list.data.length==0){
      Vue.showMessage("未检测到要导出的用户，请检查条件！")
      return
    }
    this.isSend=true
    //this.jointCondition1("planitemconditionList","checkplanitems")
    let res=await this.http.load('POST','api/af-safecheck/logic/exportfile',
      {
        "data": {
          "body": {
            "data": {
              "condition": this.user.search.search({
                "f_filialeid": "ui.f_filialeid={}",
                "userinfocode": "ui.f_userinfo_code='{}'",
                "username": "ui.f_user_name like '%{}%'",
                "useraddress": "ua.f_address like '%{}%'",
                "userType":"uf.f_user_type='{}'",
                "f_residential_area":"ua.f_residential_area = '{}'",
                "f_building":"ua.f_building='{}'",
                "f_unit":"ua.f_unit='{}'",
                "f_user_state":"ui.f_user_state='{}'",
                "checkTime":"{}",
                "uploadCondition":"{}",
                "f_devices":"de.f_devices_type='{}'",
                "f_gasproperties":"sp.f_gasproperties='{}'",
                "f_meter_classify":"uf.f_meter_classify='{}'",
                "f_table_state":"uf.f_table_state='{}'",
                "f_meter_brand":"gb.f_meter_brand='{}'",
                "f_price_type":"sp.f_price_type='{}'",
                "f_price_name":"sp.f_price_name='{}'",
                "ychecked":" {}"
              }),
              "orderitem": 'f_residential_area,f_building,f_unit,f_floor,f_room',
              "f_usertype": '',
              "month": '',
              "SafeCheckSX": {"f_check_start": '', "f_check_end": ''},
              "SafeCheckCQ": '',
              "startday":"",
              "f_plan_year":new Date().getFullYear()
            },
            "field": ["f_userinfo_code:用户编号","f_user_name:用户名称", "f_user_type:用户类型","f_user_phone:用户电话","f_residential_area:小区名称","f_last_check_date:最后一次安检时间","f_last_check_state:最后一次安检状态","f_address:详细地址"],
            "templateName": '用户安检情况',
            "sqlName": "FetchUserFileByOrgNoRuHuSXQTS"
          },
        }
      }
      ,{resolveMsg: null, rejectMsg: null})
    console.log("excel结果---"+JSON.stringify(res))
    let link = document.createElement('a');
    let path = res.data[0].filename
    //webapps这个是在服务器上导出用的
    let pathName = "http://" + location.host + "/webapps" + path.split('webapps')[1]
    //excel这个是在本地导出用的
    link.href = pathName;
    link.download = path.split('excel/')[1];
    link.dispatchEvent(new MouseEvent('click'));
    this.isSend=false
  }

  flush(f){
    f()
  }
}
