<template>
  <div class="col-sm-12 col-xs-12 p-10">
    <accordion one-at-a-time="true">
      <panel :header="selectdata.defname" :is-open="isOpen"  type="primary">
        <app-service-view v-ref:serviceview :data="show_data" v-if="showview"></app-service-view>
      </panel>
      <panel   header='地图' :is-open="!isOpen" type="primary" v-if="selectdata.defname ==='现场勘察'">
          <div style="height: 85vh">
            <apply-map-com :selectdata="selectdata"></apply-map-com>
          </div>
      </panel>
    </accordion>
  </div>
</template>
<script>
import Vue from 'vue'
import {HttpResetClass} from 'vue-client'
import {isEmpty} from '../../Util'
// Date格式化
Date.prototype.Format = function (fmt) {
  var o = {
    'M+': this.getMonth() + 1, // 月份
    'd+': this.getDate(), // 日
    'H+': this.getHours(), // 小时
    'm+': this.getMinutes(), // 分
    's+': this.getSeconds(), // 秒
    'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
    'S': this.getMilliseconds() // 毫秒
  }
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
  }
  return fmt
}
export default {
  title: '报建流程业务控制层',
  props: ['selectdata', 'title'],
  data() {
    return {
      json_datas: null,
      data: null,
      show_data: null,
      showview: false,
      config: {},
      isOpen: true
    }
  },
  ready() {
    this.refurbish()
  },
  methods: {
    async refurbish() {
      this.showview = false
      let title=this.title
      let http = new HttpResetClass()
      let data = {
        workname: this.selectdata.processname
      }
     await  http.load('POST', `${this.$androidUtil.getProxyUrl()}/rs/logic/ApplyGetConfigs`, {
        data
      }, {resolveMsg: null, rejectMsg: null}).then((res) => {
        this.json_datas = res.data
      })
      let sum = 0
      let jsonData = {}
      if (!this.json_datas || !this.json_datas.activitys || this.json_datas.activitys.length === 0) {
        this.$showMessage("网络故障，请刷新页面")
        return
      }
      this.json_datas.activitys.forEach(item => {
        if (this.selectdata.defname === '施工信息') {
          if (item.title === '工程施工') {
            jsonData = item  // 拿到当前节点的json配置信息
            sum++ // 节点名一样的个数
          }
        }else if (this.selectdata.defname === item.title) {
          jsonData = item  // 拿到当前节点的json配置信息
          sum++ // 节点名一样的个数
        }
        return this.selectdata.defname === item.title // 拿到当前节点的json配置信息
      })

      if (sum === 0) {
        this.$showMessage(`没有在JSON配置文件中找到活动名为:(${this.selectdata.defname})的节点配置`)
        return
      }
      if (sum > 1) {
        this.$showMessage(`在JSON配置文件中找到活动名为:(${this.selectdata.defname})的节点配置:${sum}个`)
        return
      }

      this.selectdata = Object.assign({}, this.selectdata, jsonData)

      // fields 字段填充值
      for (const item of this.selectdata.fields) {
        if (!item.value) {
          item.value = null
        }

        if (!item.value && (item.default || item.default === 0) && item.type !== 'datepicker') {
          if (item.eval) {
            let user = Vue.user
            // 将PC用户信息 替换成 APP的
            item.value = eval(item.default.replace('this.$login.f', 'user'))
          } else {
            item.value = item.default
          }
        }

        if (this.selectdata[item.field]) {
          // 将json字符串格式化赋值给value
          if (String(this.selectdata[item.field]).startsWith("{")) {
            item.value = JSON.parse(this.selectdata[item.field])
          } else {
            item.value = this.selectdata[item.field]
          }
        }
        if (this.selectdata[item.field] === 0) {
          item.value = 0
        }

        // datepicker
        if (item.type === 'datepicker' && !item.value && item.default) {
          item.value = new Date().Format(`${item.format ? item.format : 'yyyy-MM-dd HH:mm:ss'}`)
        }

        // 如果配置类型为select,优先从参数列表获取options
        if (item.type === 'select' || item.type === 'checkbox') {
          if (item.param) {
            let temp = this.$appdata.getParam(item.label)

            if (temp && temp.length > 0) {
              item.options = temp
            }

            if (item.paramLabel) {
              temp = this.$appdata.getParam(item.paramLabel)
              if (temp && temp.length > 0) {
                item.options = temp
              }
            }
          }

        }
        if (item.ready) {
          item.options = await this[item.ready]()
        }

        if (item.type === 'checkbox') {
          if (this.selectdata[item.field]) {
            item.value = JSON.parse(this.selectdata[item.field])
          } else {
            item.value = []
          }
        }
        if(this.selectdata.defname === '施工信息'||this.title === '已办信息'){
          item.readonly = true
          item.disabled = true
        }
      }

      // 控制组件
      if (this.selectdata.components) {
        this.selectdata.components.forEach(item => {
          if (!item.mark) {
            item.mark = 0
          }
        })
      }
      // 控制组件
      if(this.selectdata.defname === '施工信息') {
        if (this.selectdata.components) {
          this.selectdata.components.forEach(item => {
            item.mark = 1
          })
        }
      }

      // 初始化onetomany
      if (this.selectdata.onetomany) {
        for (const item of this.selectdata.onetomany) {
          let res = null
          if (item.queryEvent) {
            res = this[item.queryEvent]()
          } else {
            let http = new HttpResetClass()
            let data = {
              tablename: item.tables[0],
              condition: `f_process_id='${this.selectdata.f_process_id}'`
            }
            res = await http.load(
              'POST',
              `${this.$androidUtil.getProxyUrl()}/rs/sql/applySingleTable`,
              // `rs/sql/applySingleTable`,
              {data: data},
              {resolveMsg: null, rejectMsg: 'onetomany查询失败'}
            )
          }

          item.rows = res.data

          // 初始化onetomany中的fields
          for (const field of item.fields) {
            if (!field.value) {
              if (field.value !== 0) {
                field.value = null
              }
            }

            if (field.default || field.default === 0) {
              field.value = field.default
            }

            // datepicker
            if (field.type === 'datepicker' && !field.value && field.default) {
              field.value = new Date().Format(`${field.format ? field.format : 'yyyy-MM-dd HH:mm:ss'}`)
            }

            if (field.type === 'select') {

              if (field.param) {
                let temp = this.$appdata.getParam(field.label)

                if (temp && temp.length > 0) {
                  field.options = temp
                }

                if (field.paramLabel) {
                  temp = this.$appdata.getParam(field.paramLabel)
                  if (temp && temp.length > 0) {
                    item.options = temp
                  }
                }
              }

            }
          }
          if(this.selectdata.defname === '施工信息'){
            // 隐藏所有操作
            item.hiddenOperate = true
          }
        }
      }

      // 初始化 buttons_fields
      for (const item of this.selectdata.buttons) {
        if (item.button_name === '下发' || item.button_name === '转派') {
          let data = {
            source: item.source,
            userid: Vue.user.id
            // userid: '51953'
          }
          if (item.sourceMethod) {
            data.source = this[item.sourceMethod]()
          }
          if (!data.source) {
            this.$showMessage("请配置获取人员表达式")
            return
          }
          let res = await this.$resetpost(
            `${this.$androidUtil.getProxyUrl()}/rs/search`,
            // `rs/search`,
            {data: data},
            {resolveMsg: null, rejectMsg: '下发人员查询失败！！！'}
          )

          let options = res.data.map(source => {
            return {
              "label": source.name,
              "value": source.id
            }
          })

          if (item.button_fields.length !== 1) {
            this.$showMessage("下发有且只能有一个字段！！！")
            return
          }

          item.button_fields[0].options = options
        }
        if (item.button_fields) {
          item.button_fields.forEach(x => {
            // 如果配置类型为select,优先从参数列表获取options
            if (x.type === 'select') {

              if (x.param) {
                let temp = this.$appdata.getParam(x.label)

                if (temp && temp.length > 0) {
                  x.options = temp
                }

                if (x.paramLabel) {
                  temp = this.$appdata.getParam(x.paramLabel)
                  if (temp && temp.length > 0) {
                    x.options = temp
                  }
                }
              }

            }
          })
        }
      }
      if(this.selectdata.defname === '施工信息'||this.title=== '已办信息'){
        this.selectdata.buttons = null
      }
      if (this.selectdata.f_apply_nature === '散户' && this.selectdata.defname === '现场勘察') {
        for (const item of this.selectdata.fields) {
          if (item.label.includes('安装户数')) {
            item.readonly = true
          }
        }
      }
      // 消除双向绑定，避免子组件（显示层）数据更改，父组件（控制层）也更改
      let temp = JSON.parse(JSON.stringify(this.selectdata))

      this.show_data = temp
      this.$nextTick(() => {
        this.showview = true
      })
    },
    // 金额转大写
    smalltoBIG(n) {
      let fraction = ['角', '分'];
      let digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
      let unit = [['元', '万', '亿'], ['', '拾', '佰', '仟']];
      let head = n < 0 ? '欠' : '';
      n = Math.abs(n);

      let s = '';

      for (var i = 0; i < fraction.length; i++) {
        s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
      }
      s = s || '整';
      n = Math.floor(n);

      for (var i = 0; i < unit[0].length && n > 0; i++) {
        let p = '';
        for (var j = 0; j < unit[1].length && n > 0; j++) {
          p = digit[n % 10] + unit[1][j] + p;
          n = Math.floor(n / 10);
        }
        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
      }
      return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整')
    },
    getLableValue(label) {
      for (const item of this.show_data.fields) {
        if (item.label === label && item.type !== 'number') {
          return item.value || ''
        }
        if (item.label === label && item.type === 'number') {
          return item.value || 0
        }
      }
    },
    getLableOptions(label) {
      for (const item of this.show_data.fields) {
        if (item.label === label) {
          return item.options
        }
      }
    },
    setLabelValue(label, value) {
      for (const item of this.show_data.fields) {
        if (item.label === label) {
          item.value = value
          this.show_data[item.field] = value
        }
      }
    },
    setLabelOptions(label, options) {
      for (const item of this.show_data.fields) {
        if (item.label === label) {
          item.options = options
        }
      }
    },
    showLabels(...labels) {
      for (const item of this.show_data.fields) {
        if (labels.includes(item.label)) {
          item.hidden = false
        }
      }
    },
    hideLabels(...labels) {
      for (const item of this.show_data.fields) {
        if (labels.includes(item.label)) {
          item.hidden = true
        }
      }
    },
    showButtons(...buttons) {
      for (const item of this.show_data.buttons) {
        if (buttons.includes(item.button_name)) {
          item.hidden = false
        }
      }
    },
    hideButtons(...buttons) {
      for (const item of this.show_data.buttons) {
        if (buttons.includes(item.button_name)) {
          item.hidden = true
        }
      }
    },
    requiredLabels(...labels) {
      for (const item of this.show_data.fields) {
        if (labels.includes(item.label)) {
          item.required = true
        }
      }
    },
    electiveLabels(...labels) {
      for (const item of this.show_data.fields) {
        if (labels.includes(item.label)) {
          item.required = false
        }
      }
    },
    readonlyLabels(...labels) {
      for (const item of this.show_data.fields) {
        if (labels.includes(item.label)) {
          item.readonly = true
          item.disabled = true
        }
      }
    },
    readwriteLabels(...labels) {
      for (const item of this.show_data.fields) {
        if (labels.includes(item.label)) {
          item.readonly = false
          item.disabled = false
        }
      }
    },
    disabledButtons(...buttons) {
      for (const item of this.show_data.buttons) {
        if (buttons.includes(item.button_name)) {
          item.disabled = true
        }
      }
    },
    enableButtons(...buttons) {
      for (const item of this.show_data.buttons) {
        if (buttons.includes(item.button_name)) {
          item.disabled = false
        }
      }
    },
    showComponents(...titles) {
      for (const item of this.show_data.components) {
        if (titles.includes(item.title) && item.device === 'app') {
          item.hidden = false
        }
      }
    },
    hideComponents(...titles) {
      for (const item of this.show_data.components) {
        if (titles.includes(item.title) && item.device === 'app') {
          item.hidden = true
        }
      }
    },
    async checkDuplicate(index) {
      let http = new HttpResetClass()
      let data = {
        tablename: 't_apply',
        condition: `${this.show_data.fields[index].field} = '${this.show_data.fields[index].value}'`
      }
      let res = await http.load('POST', `${this.$androidUtil.getProxyUrl()}/rs/sql/applySingleTable`, {data: data}, {
        resolveMsg: null,
        rejectMsg: `${this.show_data.fields[index].label}查询失败`
      })
      if (res.data.length > 0) {
        this.show_data.fields[index].value = null
        this.$showMessage(`${this.show_data.fields[index].label}已存在！！！`)
      }
    },
    async breakControl() {
      if (this.show_data.id) {
        let data = {
          condition: `u.id = ${this.show_data.id}`,
          data: {
            userid: Vue.user.id,
            f_filiale: "榆林."+Vue.user.orgs
          }
        }
        let url =`${this.$androidUtil.getProxyUrl()}/rs/sql/checkuser`
        if (this.show_data.f_apply_type === '管线建设'){
          url =`${this.$androidUtil.getProxyUrl()}/rs/sql/getGuanXianApply`
        }
        let res = await this.$resetpost(
          url,
          {data: data},
          {resolveMsg: null, rejectMsg: '数据更新失败，请手查询更新！！！'}
        )

        this.selectdata = res.data[0]
        this.selectdata.f_building=this.show_data.f_building
        this.selectdata.f_unit=this.show_data.f_unit
        this.selectdata.f_room=this.show_data.f_room
        this.selectdata.pageIndex=this.show_data.pageIndex
      } else {
        this.selectdata = servicedata
      }

      this.refurbish()
    },
    // ------------------------------
    async getConstructionWorker() {
      let data = {
        source: 'this.getParentByType($organization$).getChildByName($建设单位$).getChildren()',
        userid: Vue.user.id
      }

      let res = await this.$resetpost(
        `${this.$androidUtil.getProxyUrl()}/rs/search`,
        {data: data},
        {resolveMsg: null, rejectMsg: '现场负责人查询失败！！！'}
      )

      return res.data.map(item => {
        return {
          label: item.name,
          value: item.id
        }
      })
    },
    //获取下发人
    getSource () {
      return  'this.getParentByType($organization$).getChildByName($'+ Vue.user.f_parentname + '$).getChildren()'
    },
    async getUserName() {
      let data = {
        tablename: 't_user',
        condition: `id='${this.selectdata.f_construction_unit_id}'`
      }
      let res = await this.$resetpost(
        '${this.$androidUtil.getProxyUrl()}/rs/sql/applySingleTable',
        {data: data},
        {resolveMsg: null, rejectMsg: null}
      )
      return res.data.map(item => {
        return {
          label: item.name,
          value: item.id
        }
      })
    },
    // 安装单位签字人
    async getConstructionUnitId () {
      let data = {
        source: '',
        userid: Vue.user.id
      }
      data.source = 'this.getParentByType($organization$).getChildByName($'+ Vue.user.f_department_name + '$).getChildren()'
      let res = await this.$resetpost(
        `${this.$androidUtil.getProxyUrl()}/rs/search`,
        {data: data},
        {resolveMsg: null, rejectMsg: '安装单位施工班组查询失败！！！'}
      )

      return res.data.map(item => {
        return {
          label: item.name,
          value: item.id
        }
      })
    },
    // 安装单位负责人
    async getConstructionUnit() {
      let data = {
        source: 'this.getParentByType($organization$).getChildByName($工程施工队$).getChildren()',
        userid: Vue.user.id
      }

      let res = await this.$resetpost(
        `${this.$androidUtil.getProxyUrl()}/rs/search`,
        {data: data},
        {resolveMsg: null, rejectMsg: '安装单位人员查询失败！！！'}
      )

      return res.data.map(item => {
        return {
          label: item.name,
          value: item.id
        }
      })
    },
    // 建设单位
    async getConstructOperator() {
      let data = {
        source: 'this.getParentByType($organization$).getChildByName($建设单位$).getChildren()',
        userid: Vue.user.id
      }

      let res = await this.$resetpost(
        `${this.$androidUtil.getProxyUrl()}/rs/search`,
        {data: data},
        {resolveMsg: null, rejectMsg: '建设单位人员查询失败！！！'}
      )

      return res.data.map(item => {
        return {
          label: item.name,
          value: item.id
        }
      })
    },
    // 监理单位
    async getSupervisorOperator() {
      let data = {
        source: 'this.getParentByType($organization$).getChildByName($监理单位$).getChildren()',
        userid: Vue.user.id
      }

      let res = await this.$resetpost(
        `${this.$androidUtil.getProxyUrl()}/rs/search`,
        {data: data},
        {resolveMsg: null, rejectMsg: '监理单位人员查询失败！！！'}
      )
      for (const item of this.selectdata.fields) {
        if (item.label === '监理单位') {
          item.value = res.data[0].id
          this.selectdata[item.field] = res.data[0].id
        }
      }
      return res.data.map(item => {
        return {
          label: item.name,
          value: item.id
        }
      })
    },
    // 监理现场负责人
    async getSupervisorOperatorId () {
      let data = {
        source: 'this.getParentByType($organization$).getChildByName($监理班组$).getChildren()',
        userid: Vue.user.id
      }
      let res = await this.$resetpost(
        `${this.$androidUtil.getProxyUrl()}/rs/search`,
        {data: data},
        {resolveMsg: null, rejectMsg: '监理单位人员查询失败！！！'}
      )
      return res.data.map(item => {
        return {
          label: item.name,
          value: item.id
        }
      })
    },
    // 土建单位
    async getEngineeringOperator() {
      let data = {
        source: 'this.getParentByType($organization$).getChildByName($土建单位$).getChildren()',
        userid: Vue.user.id
      }

      let res = await this.$resetpost(
        `${this.$androidUtil.getProxyUrl()}/rs/search`,
        {data: data},
        {resolveMsg: null, rejectMsg: '土建单位人员查询失败！！！'}
      )

      let result = res.data.map(item => {
        return {
          label: item.name,
          value: item.id
        }
      })
      result.push({label: '用户自理', value: '用户自理'})
      result.push({label:'无',value:'无'})
      return result
    },
    // 检测单位
    async getCheckOperator() {
      let data = {
        source: 'this.getParentByType($organization$).getChildByName($检测单位$).getChildren()',
        userid: Vue.user.id
      }

      let res = await this.$resetpost(
        `${this.$androidUtil.getProxyUrl()}/rs/search`,
        {data: data},
        {resolveMsg: null, rejectMsg: '检测单位人员查询失败！！！'}
      )

      let result = res.data.map(item => {
        return {
          label: item.name,
          value: item.id
        }
      })
      result.push({label:'无',value:'无'})
      return result
    },
    // 获取气表品牌
    async getMeterBrand() {
      let data = {}

      let http = new HttpResetClass()
      let res = await http.load(
        'POST',
        `${this.$androidUtil.getProxyUrl()}/rs/sql/getMeterBrand`,
        {data: data},
        {resolveMsg: null, rejectMsg: '气表品牌查询失败！！！'}
      )

      return res.data
    },
    // 获取小区
    async getResidentialArea() {
      let data = {
        tablename: 't_area_address',
        condition: `f_filiale  like '%${"榆林."+Vue.user.orgs}%' and f_area_status = '启用'`
      }
      let http = new HttpResetClass()
      let res = await http.load(
        'POST',
        `${this.$androidUtil.getProxyUrl()}/rs/sql/applySingleTable`,
        {data: data},
        {resolveMsg: null, rejectMsg: '小区查询失败！！！'}
      )
      return res.data.map(item => {
        return {
          label: item.f_residential_area,
          value: item.id
        }
      })
    },
    //现场勘察
    async prospectingBefore() {
      let data = {
        tablename: 't_files',
        condition: `f_blobid = '${this.selectdata.f_process_id}' and defname = '现场勘察' and fremarks = '报装手机签字文件'`
      }
      let http = new HttpResetClass()
      let res = await http.load(
        'POST',
        `${this.$androidUtil.getProxyUrl()}/rs/sql/applySingleTable`,
        {data: data},
        {resolveMsg: null, rejectMsg: null}
      )
      if (res.data.length <= 0) {
        this.$showMessage('现场勘察未签字，无法提交！！！')
        throw '现场勘察未签字，无法提交！'
      }
    },
    // 施工前置
    async constructionBefore() {
      await this.userSignBefore()
      if (this.show_data.f_apply_nature !== '分户挂表') {
        let http = new HttpResetClass()
        let data = {
          condition: `ui.f_process_id = '${this.show_data.f_process_id}' and f_meternumber is null and f_gasbrand_id is not null `
        }
        let res = await http.load(
          'POST',
          `${this.$androidUtil.getProxyUrl()}/rs/sql/countApplyUserinfo`,
          {data: data},
          {
            resolveMsg: null,
            rejectMsg: '安装明细查询失败！！！'
          })
        if (res.data[0].num > 0) {
          this.$showMessage(`还有${res.data[0].num}户未表号未录入，无法提交`)
          throw `还有${res.data[0].num}户未表号未录入，无法提交`
        }
      }
    },
    async userSignBefore() {
      let http = new HttpResetClass()
      let data = {
        tablename: 't_files',
        condition: `f_blobid = '${this.selectdata.f_process_id}' and defname = '${this.selectdata.defname}' and fremarks = '报装手机签字文件'`
      }
      let res = await http.load(
        'POST',
        `${this.$androidUtil.getProxyUrl()}/rs/sql/applySingleTable`,
        {data: data},
        {resolveMsg: null, rejectMsg: null}
      )
      if (res.data.length <= 0) {
        this.$showMessage('用户未签字，无法生成签字流程！！！')
        throw '用户未签字，无法生成签字流程！'
      }
    },
    signBefore() {
      if (this.show_data.defname === '检测单位签字') {
        if (isEmpty(this.show_data.f_check_sign)) {
          this.$showMessage(`签字后才可提交！！!`)
          throw `签字后才可提交！！!`
        }
        this.show_data.f_check_operator = Vue.user.name
        this.show_data.f_check_date = new Date().Format('yyyy-MM-dd HH:mm:ss')
        this.show_data.employeetemplate = this.show_data.f_build_operator_id
      }
      if (this.show_data.defname === '安装单位签字') {
        if (isEmpty(this.show_data.f_build_sign)) {
          this.$showMessage(`签字后才可提交！！!`)
          throw `签字后才可提交！！!`
        }
        this.show_data.f_build_operator = Vue.user.name
        this.show_data.f_build_date = new Date().Format('yyyy-MM-dd HH:mm:ss')
        this.show_data.employeetemplate = this.show_data.f_engineering_operator_id
        if (this.show_data.f_engineering_operator_id === '用户自理' || this.show_data.f_engineering_operator_id === '无') {
          this.show_data.f_engineering_operator = this.show_data.f_engineering_operator_id
          this.show_data.f_engineering_date = new Date().Format('yyyy-MM-dd HH:mm:ss')
          this.show_data.employeetemplate = this.show_data.f_supervisor_operator_id
        }
      }
      if (this.show_data.defname === '土建单位签字') {
        if (isEmpty(this.show_data.f_engineering_sign)) {
          this.$showMessage(`签字后才可提交！！!`)
          throw `签字后才可提交！！!`
        }
        this.show_data.f_engineering_operator = Vue.user.name
        this.show_data.f_engineering_date = new Date().Format('yyyy-MM-dd HH:mm:ss')
        this.show_data.employeetemplate = this.show_data.f_supervisor_operator_id
      }
      if (this.show_data.defname === '监理单位签字') {
        if (isEmpty(this.show_data.f_supervisor_sign)) {
          this.$showMessage(`签字后才可提交！！!`)
          throw `签字后才可提交！！!`
        }
        this.show_data.f_supervisor_operator = Vue.user.name
        this.show_data.f_supervisor_date = new Date().Format('yyyy-MM-dd HH:mm:ss')
        this.show_data.employeetemplate = this.show_data.f_construct_operator_id
      }
      if (this.show_data.defname === '建设单位签字') {
        if (isEmpty(this.show_data.f_construct_sign)) {
          this.$showMessage(`签字后才可提交！！!`)
          throw `签字后才可提交！！!`
        }
        this.show_data.f_construct_operator = Vue.user.name
        this.show_data.f_construct_date = new Date().Format('yyyy-MM-dd HH:mm:ss')
      }
    },
    //分户挂表生成安检单
    async getChecklist() {
      let http = new HttpResetClass()
      let data = {
        f_process_id: this.selectdata.f_process_id,
        f_userinfo_id: this.selectdata.f_userinfo_id,
        user: Vue.user
      }
      let res = await http.load(
        'POST',
        `${this.$androidUtil.getProxyUrl()}/rs/logic/getChecklist`,
        {data: data},
        {resolveMsg: null, rejectMsg: null}
      )
    },
    //工商户验证表具类型是否需选择
    async meterBrandCheck() {
      let data = {
        f_process_id: this.selectdata.f_process_id,
        orgid:Vue.user.orgid
      }
      let http = new HttpResetClass()
      let res = await http.load(
        'POST',
        `${this.$androidUtil.getProxyUrl()}/rs/sql/meterCheck`,
        {data: data},
        {resolveMsg: null, rejectMsg: null}
      )
      if (res.data[0].num > 0){
        this.$showMessage(`还有${res.data[0].num}处未选择表具，请选择后提交！`)
        throw null
      }
    },
    // 安装户数
    async installCountCheck() {
      let data = {
        tablename: 't_userinfo',
        condition: `f_process_id = '${this.show_data.f_process_id}' and f_user_state != '销户'`,
      }

      let http = new HttpResetClass()
      let res = await http.load(
        'POST',
        `${this.$androidUtil.getProxyUrl()}/rs/sql/applySingleTable`,
        {data: data},
        {resolveMsg: null, rejectMsg: '用户数量查询失败'}
      )
      this.setLabelValue('安装户数',res.data.length)
    },
    async stopApply () {
      console.log('终止报建！！！！！')

      if (this.show_data.defname === '报建受理') {
        this.show_data.f_stop_reason = this.show_data.f_accept_result
      }
      if (this.show_data.defname === '现场勘察') {
        this.show_data.f_stop_reason = this.show_data.f_prospecting_result
      }

      let data = {
        apply: this.show_data,
        user: Vue.user
      }

      let res = await this.$resetpost(
        `${this.$androidUtil.getProxyUrl()}/rs/logic/stopApply`,
        {data: data},
        {resolveMsg: null, rejectMsg: '终止报建失败！！！'}
      )

      this.$dispatch('confirm')

      throw '终止报建！！！'
    },
    // 户内出单日期
    getOutdoorsTime () {
      for (const item of this.selectdata.fields) {
        console.log('是否进入')
        if (item.label === '户内出单日期') {
          item.value = this.selectdata.f_release_date
          this.selectdata[item.field] = item.value
          console.log('当前出单时间',item.value)
        }else if(item.label === '庭院出单日期'){
          item.value = this.selectdata.f_release_date
          this.selectdata[item.field] = item.value
        }
      }
    },
    getGaiXianType () {
      return [{label: "隐患整改", value: "隐患整改"},
        {label: "改造工程", value: "改造工程"},
        {label: "改线工程", value: "改线工程"},
        {label: "老旧小区", value: "老旧小区"}]
    },
    //获取缴费日期
    async getChargeDate() {
      let data = {
        tablename: 'activityins',
        condition: `processid = '${this.selectdata.f_process_id}' and defname = '报装缴费'`,
      }

      let http = new HttpResetClass()
      let res = await http.load(
        'POST',
        `${this.$androidUtil.getProxyUrl()}/rs/sql/applySingleTable`,
        {data: data},
        {resolveMsg: null, rejectMsg: null}
      )
      for (const item of this.selectdata.fields) {
        if (item.label === '缴费日期') {
          item.value = res.data[0].finishtime
          this.selectdata[item.field] = item.value
        }
      }
    },
    async getSingAct() {
      let data = {
        f_process_id: this.selectdata.f_process_id
      }
      let http = new HttpResetClass()
      let res = await http.load(
        'POST',
        `${this.$androidUtil.getProxyUrl()}/rs/sql/getSingAct`,
        {data: data},
        {resolveMsg: null, rejectMsg: '签字状态查询失败！！！'}
      )
      if (res.data.length > 0) {
        for (const item of this.selectdata.fields) {
          if (item.label === '签字所在环节') {
            item.value = res.data[0].defname
            this.selectdata[item.field] = item.value
          }
        }
      }
    },
    getYiFang() {
      return [{label: '榆林榆川天然气', value: '榆林榆川天然气'},
        {label: this.selectdata.f_user_name, value: this.selectdata.f_user_name},
        {label: '无', value: '无'}]
    },
    async repair() {
      let data = {
        f_process_id: this.show_data.f_process_id
      }
      let http = new HttpResetClass()
      let res = await http.load(
        'POST',
        `${this.$androidUtil.getProxyUrl()}/rs/logic/updateRepair`,
        {data: data},
        {resolveMsg: null, rejectMsg: '维修工单状态修改！！！'}
      )
      this.$dispatch('loadPage')
      throw ''
    },
    changeDispatch(value){
      if (value === '维修安检中心'){
        this.hideLabels('现场项目负责人', '安装单位', '建设单位', '监理单位', '土建单位', '检测单位', '户内出单日期', '户内回单日期'
          , '户内施工备注', '庭院出单日期', '庭院回单日期', '庭院施工备注', '是否发起签字', '签字是否完成', '签字所在环节')
        this.hideButtons('签字')
        this.electiveLabels('现场项目负责人', '安装单位', '建设单位', '监理单位', '土建单位', '检测单位', '户内出单日期', '户内回单日期'
          , '户内施工备注', '庭院出单日期', '庭院回单日期', '庭院施工备注', '是否发起签字', '签字是否完成', '签字所在环节')
      }
      if (value === '施工工队'){
        this.showLabels('现场项目负责人', '安装单位', '建设单位', '监理单位', '土建单位', '检测单位', '户内出单日期', '户内回单日期'
          , '户内施工备注', '庭院出单日期', '庭院回单日期', '庭院施工备注', '是否发起签字', '签字是否完成', '签字所在环节')
        this.requiredLabels('现场项目负责人', '安装单位', '建设单位', '监理单位', '土建单位', '检测单位', '现场项目负责人', '是否发起签字', '签字是否完成', '签字所在环节')
      }
    },
    geIsOpen(){
      this.isOpen = false
    }
  },
  events: {
    // 强制开关阀
    async 'onOffValve'() {
      let data = {
        condition: `ui.f_userinfo_id = '${this.show_data.f_userinfo_id}'`
      }
      let http = new HttpResetClass()
      let res = await http.load(
        'POST',
        `${this.$androidUtil.getProxyUrl()}/rs/sql/getApplyUserinfo`,
        {data: data},
        {resolveMsg: null, rejectMsg: '档案获取失败！！！'}
      )

      let userinfo = res.data[0]

      data = {
        condition: `t_userfiles.f_meternumber = '${userinfo.f_meternumber}'`,
        contentData: {
          isOpen: this.show_data.button.button_name === '强制开阀' ? 1 : 0
        },
        inputtor: Vue.user.name,
        instructTitle: this.show_data.button.button_name === '强制开阀' ? '开阀' : '关阀',
        instructType: '阀门控制',
        meterBrandName: userinfo.f_alias
      }
      res = await http.load(
        'POST',
        `${this.$androidUtil.getProxyUrl()}/rs/logic/saveInstruct`,
        {data: data},
        {resolveMsg: null, rejectMsg: `${this.show_data.button.button_name}失败！！！`}
      )

      data = {
        f_user_id: userinfo.f_user_id,
        f_userinfo_id: userinfo.f_userinfo_id,
        record: {
          f_filiale: "榆林."+Vue.user.orgs,
          f_instruct_meta_data: this.show_data.button.button_name === '退出强制状态' ? '退出强制阀控' : '进入强制阀控',
          f_instruct_title: this.show_data.button.button_name === '退出强制状态' ? '退出强制阀控' : '进入强制阀控',
          f_instruct_type: '阀门控制',
          f_meternumber: userinfo.f_meternumber,
          f_operator: Vue.user.name,
          f_outlets: userinfo.f_outlets,
          f_reason: this.show_data.button.f_reason,
          f_user_id: userinfo.f_user_id,
          f_userinfo_id: userinfo.f_userinfo_id
        },
        state: this.show_data.button.button_name === '退出强制状态' ? 0 : 1,
      }

      res = await http.load(
        'POST',
        `${this.$androidUtil.getProxyUrl()}/rs/logic/updateNetWorkValve`,
        {data: data},
        {resolveMsg: '执行成功！！！', rejectMsg: `执行失败！！！`}
      )

    },
    // 修改用户档案
    async 'updateUserinfoState'() {
      let data = {
        f_userinfo_id: this.show_data.f_userinfo_id
      }
      let http = new HttpResetClass()
      let res = await http.load(
        'POST',
        `${this.$androidUtil.getProxyUrl()}/rs/logic/updateUserinfoState`,
        {data: data},
        {resolveMsg: '该用户档案已为正常档案，可进行开关阀操作！！！', rejectMsg: '档案状态修改失败！！！'}
      )

      this.showButtons('退出强制状态', '强制关阀')
      this.hideButtons('转正式档案')
    },
    //开始签字流程
    async 'startSignActivity'() {
      this.hideButtons('签字')

      if(this.show_data.f_apply_type !== '管线建设'){
        await this.constructionBefore()
      }
      let data = {
        apply: this.show_data,
        user: Vue.user
      }

      let res = await this.$resetpost(
        `${this.$androidUtil.getProxyUrl()}/rs/logic/startSignActivity`,
        {data: data},
        {resolveMsg: '签字流程已发起！！！', rejectMsg: '签字发起失败！！！'}
      )

      this.breakControl()
    },
    // 工程施工初始化
    async 'buildReadyEvent'() {
      if (this.getLableValue('是否发起签字') === '是') {
        this.hideButtons('签字')
      }
      let http = new HttpResetClass()
      console.log("当前流程",this.show_data.f_apply_type)
      if (isEmpty(this.show_data.f_meter_brand)) {
        return
      }else {
        if (this.show_data.f_meter_brand === 'null') {
          this.setLabelOptions('气表型号', [{label: '无', value: 'null'}])
          return
        }
         let data = {
          f_gasbrand_id: this.show_data.f_meter_brand
        }
        let res = await http.load(
          'POST',
          `${this.$androidUtil.getProxyUrl()}/rs/sql/getGasModel`,
          {data: data},
          {resolveMsg: null, rejectMsg: '气表型号查询失败！！！'}
        )
        this.setLabelOptions('气表型号', res.data)
      }
      if (this.show_data.f_apply_type === '分户挂表') {
        let data = {
          condition: `ui.f_userinfo_id = '${this.show_data.f_userinfo_id}'`
        }
        let http = new HttpResetClass()
        let res = await http.load(
          'POST',
          `${this.$androidUtil.getProxyUrl()}/rs/sql/getApplyUserinfo`,
          {data: data},
          {resolveMsg: null, rejectMsg: '档案状态获取失败！！！'}
        )
        setTimeout(() => {
          if (res.data[0].f_meter_classify === '物联网表') {
            if (res.data[0].f_user_state === '正常') {
              this.showButtons('退出强制状态', '强制关阀')
              this.hideButtons('转正式档案')
            } else {
              this.showButtons('转正式档案')
              this.hideButtons('退出强制状态', '强制关阀')
            }
          }
        }, 1000)
      }
    },
    // 气表品牌失去焦点
    async 'meterBrandChenge' (index) {
      if (isEmpty(this.show_data.f_meter_brand)) {
        return
      }
      this.setLabelValue('气表型号', null)
      let data = {
        f_gasbrand_id: this.show_data.f_meter_brand
      }
      let http = new HttpResetClass()
      let res = await http.load(
        'POST',
        `${this.$androidUtil.getProxyUrl()}/rs/sql/getGasModel`,
        {data: data},
        {resolveMsg: null, rejectMsg: '气表型号查询失败！！！'}
      )

      this.setLabelOptions('气表型号', res.data)
    },
    // 安装户数失去焦点
    'installCountChange'(index) {
      if (isEmpty(this.show_data.f_install_count)) {
        return
      }
      if (Number(this.show_data.f_install_count) > Number(this.show_data.f_apply_count)) {
        this.$showMessage('安装数已超过申请数！！！')
        // this.setLabelValue('安装户数', null)
        // this.setLabelValue('安装点数', null)
        // return
      }

      if (Number(this.show_data.f_install_count) <= 0) {
        this.$showMessage('至少有一个用户！！！')
        this.setLabelValue('安装户数', null)
        this.setLabelValue('安装点数', null)
        return
      }
    },
    'complyInstallation'(index) {
      if (this.show_data.defname === '报建受理'){
        if (this.show_data.f_accept_install === '否') {
          console.log("测试")
          this.hideButtons('下发','提交')
          this.showButtons('终止')
        } else {
          this.hideButtons('终止')
          this.showButtons('下发','提交')
        }
      }
      if (this.show_data.defname === '现场勘察'){
        if (this.show_data.f_survey_opinion === '否') {
          console.log("测试")
          this.hideButtons('下发','提交')
          this.showButtons('终止')
        } else {
          this.hideButtons('终止')
          this.showButtons('下发','提交')
        }
      }
      if (this.show_data.defname === '报建受理' || this.show_data.defname === '现场勘察'){
        this.installCountCheck()
      }
    },
    //搜索小区
    'selectArea' (val,index) {
      let pcdText = `and f_residential_area like '%${val}%'`
      let data = {
        tablename: 't_area_address',
        condition: `f_filiale like '%${"榆林."+Vue.user.orgs}%' and f_area_status = '启用' ${pcdText}`
      }
      new HttpResetClass().load("POST", `${this.$androidUtil.getProxyUrl()}/rs/sql/applySingleTable`, {data:data}, {resolveMsg: null, rejectMsg: null}).then((res)=>{
        console.log('请求发送完成！！！！！'+JSON.stringify(res))
        if(res.data.length>0){
          this.setLabelOptions('小区/巷道', res.data.map(item => {
            return {
              label: item.f_residential_area,
              value: item.id
            }
          }))
        }
      })
    },
    'changeDispatching'(index){
      if (this.show_data.fields[index].value === '安检维修中心'){
        this.hideLabels('现场项目负责人', '安装单位', '建设单位', '监理单位', '土建单位', '检测单位')
        this.electiveLabels('现场项目负责人', '安装单位', '建设单位', '监理单位', '土建单位', '检测单位')
      }else if (this.show_data.fields[index].value === '施工工队'){
        this.showLabels('现场项目负责人', '安装单位', '建设单位', '监理单位', '土建单位', '检测单位')
        this.requiredLabels('现场项目负责人', '安装单位', '建设单位', '监理单位', '土建单位', '检测单位')
      }
    },
    'getRefund'(index){
      if (this.show_data.fields[index].value === '否'){
        this.hideLabels('退费金额', '退款项')
        this.electiveLabels('退费金额', '退款项')
      }else if (this.show_data.fields[index].value === '是'){
        this.showLabels('退费金额', '退款项')
        this.requiredLabels('退费金额', '退款项')
      }
    },
    'hasTrouble'(index) {
      if (this.show_data.fields[index].value === '有纠纷'){
        this.hideButtons('提交', '签字', '图纸变更')
        this.showLabels('纠纷原因')
      }else {
        this.showButtons('提交', '签字', '图纸变更')
        this.hideLabels('纠纷原因')
      }
    },
    // ===========================================
    'initializtionView'() {
      if (this.show_data.f_apply_type === '民用报建' && this.show_data.f_apply_nature === '散户') {
        this.hideLabels('营业执照', '小区/巷道')
        this.electiveLabels('营业执照', '购货单位识别号', '购货单位银行账号', '购货单位地址电话', '小区/巷道')
      }
      if (this.show_data.f_apply_type === '民用报建' && this.show_data.f_apply_nature === '小区') {
        this.showLabels('营业执照', '小区/巷道', '小区名称')
        this.requiredLabels( '小区/巷道')
        this.hideComponents('用户花名单')
      }
    },
    'breakControl'() {
      this.breakControl()
    },
    // 检查重复
    'checkRepeat'(index) {
      this.checkDuplicate(index)
    },
    async 'button'() {
      if (this.show_data.button.before) {
        //判断当前环节
        if(this.show_data.defname=='现场勘察'||this.show_data.defname=='工程派工' ||this.show_data.defname=='工程施工'||this.show_data.defname=='点火通气'  ||this.show_data.defname=='监理单位派工' ||this.show_data.defname=='工程队派工' ||this.show_data.defname=='检测单位签字'  ||this.show_data.defname=='土建单位签字' ||this.show_data.defname=='监理单位签字' ||this.show_data.defname=='建设单位签字'){
          if(this.show_data.button.button_name=='提交' || this.show_data.button.button_name=='保存' || this.show_data.button.button_name=='退回'   || this.show_data.button.button_name=='终止' ){
            let res = await this.$showMessage('是否需要继续此次操作')
            if (res === 'cancel') {
              return
            }else{
              await this[this.show_data.button.before]()
            }
          }
        }
      }else{
        //判断当前环节
        if(this.show_data.defname=='现场勘察'||this.show_data.defname=='工程派工' ||this.show_data.defname=='工程施工'||this.show_data.defname=='点火通气'  ||this.show_data.defname=='监理单位派工' ||this.show_data.defname=='工程队派工'){
          if(this.show_data.button.button_name=='提交' || this.show_data.button.button_name=='保存' || this.show_data.button.button_name=='退回'){
            let res = await this.$showMessage('是否需要继续此次操作')
            if (res === 'cancel') {
              return
            }
          }
        }

      }
      // 点击重置按钮就重置数据
      if (this.show_data.button.button_name === '重置') {
        this.$dispatch('breakControl', this.selectdata)
        return
      }

      this.show_data.start_activity = this.json_datas.start_activity
      this.show_data.xmlfilename = this.json_datas.workflow_xmlfilename

      let data = {
        apply: this.show_data,
        user: Vue.user
      }
      console.log("当前提交数据",this.show_data)
      let res = await this.$resetpost(
        `${this.$androidUtil.getProxyUrl()}/rs/logic/ApplyProductService`,
        {data: data},
        {resolveMsg: null, rejectMsg: '数据保存失败'}
      )

      if (this.show_data.button.after) {
        this[this.show_data.button.after]()
      }
      // 返回上层
      this.$dispatch('confirm')
    },
    'locationclick' (res) {
      console.log('/*/*/*/*/*/*/*/*/*/*/*/*/*/**/*/*/*/*')
      if (res.pname){
        this.setLabelValue('定位地址', res.pname + res.cityname + res.adname + res.address + res.name)
      }else {
        this.setLabelValue('定位地址', res.province + res.city + res.address + res.name)
      }
      this.show_data.f_lng = res.location.lng
      this.show_data.f_lat = res.location.lat
      this.isOpen = !this.isOpen
    },
    selectSearch (val, index) {},
    // 失去焦点出触发事件
    'onchange'(index) {
    },
    'onblur'(index) {
    },
    'oninput'(index) {
    },
    async 'onchangeModal'(index, fieldIndex) {
    },
    async 'onblurModal'(index, fieldIndex) {

    },
    async 'oninputModal'(index, fieldIndex) {

    },
    async 'onetomanydelete'(index, rowIndex) {

      let http = new HttpResetClass()

      let res = await http.load(
        'DELETE',
        `${this.$androidUtil.getProxyUrl()}/rs/entity/${this.show_data.onetomany[index].tables[0]}/${this.show_data.onetomany[index].rows[rowIndex].id}`,
        null,
        {resolveMsg: null, rejectMsg: '删除失败！！！'}
      )
      res = await this.$resetpost(
        `${this.$androidUtil.getProxyUrl()}/rs/entity/t_apply`,
        this.show_data
      )
      this.breakControl()
    },
    async 'onetomanyupdate'(index, rowIndex) {
      let data = this.show_data.onetomany[index].rows[rowIndex]

      this.show_data.onetomany[index].fields.forEach(item => {
        data[item.field] = item.value
      })
      let res = await this.$resetpost(
        `${this.$androidUtil.getProxyUrl()}/rs/entity/${this.show_data.onetomany[index].tables[0]}`,
        data
      )
      res = await this.$resetpost(
        `${this.$androidUtil.getProxyUrl()}/rs/entity/t_apply`,
        this.show_data
      )
      this.breakControl()
    },
    async 'onetomanyadd'(index) {
      let data = {
        f_process_id: this.show_data.f_process_id,
        f_operator_id: Vue.user.id,
        f_operator: Vue.user.name,
        f_operation_date: new Date().Format('yyyy-MM-dd HH:mm:ss'),
        f_orgid: Vue.user.orgid,
        f_orgname: "榆林."+Vue.user.orgs
      }
      this.show_data.onetomany[index].fields.forEach(item => {
        data[item.field] = item.value
      })
      let res = await this.$resetpost(
        `${this.$androidUtil.getProxyUrl()}/rs/entity/${this.show_data.onetomany[index].tables[0]}`,
        data
      )
      res = await this.$resetpost(
        `${this.$androidUtil.getProxyUrl()}/rs/entity/t_apply`,
        this.show_data
      )
      this.breakControl()
    },
    'onbutchange'(index) {

    },
    'onbutblur'(index) {

    },
    'onbutinput'(index) {

    }
  },
  watch: {}
}
</script>
<style scoped>
</style>
