<template>
  <service-view v-ref:service_show :data="show_data" v-if="showview"></service-view>
</template>
<script>
  import {HttpResetClass} from 'vue-client'
  import {isEmpty} from "../../../../../../Util";
  import serviceView   from "./ServiceView.vue";
  // 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: '报建监控控制层',
    components: {
      serviceView
    },
    props: {
      selectdata: {
        type: Object
      },
      nodeSnapshot: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        data: null,    // 展示的数据
        json_datas: null, // json配置数据结构
        showview: false, // 控制显示层显示
        show_data: null,
        config: {}
      }
    },
    created () {
      this.refurbish()
    },
    methods: {
      // 初始化模块
      async refurbish() {
        this.json_datas = this.$workflow_vue
        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 === 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) {
              item.value = eval(item.default)
            } 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 = []
            }
          }

          this.selectdata[item.field] = item.value

          item.readonly = true
          item.disabled = true
        }

        // 控制组件
        if (this.selectdata.components) {
          this.selectdata.components.forEach(item => {
            item.mark = 1
            if (item.supervisory && this[item.supervisory]()) {
              item.mark = 0
            }
          })
        }

        // 初始化onetomany
        if (this.selectdata.onetomany) {
          for (const item of this.selectdata.onetomany) {
            let res = null
            if (item.queryEvent) {
              res = this[item.queryEvent]()
            } else {
              let data = {
                tablename: item.tables[0],
                condition: `f_process_id='${this.selectdata.f_process_id}'`
              }
              res = await this.$resetpost(
                'rs/sql/apply_singleTable',
                {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') {

                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
                  }
                }

              }
            }

            // 隐藏所有操作
            item.hiddenOperate = true
            if (item.supervisory && this[item.supervisory]()) {
              item.hiddenOperate = false
            }
          }
        }

        // 去除button
        this.selectdata.buttons = null

        // 完成时间和完成人,部门，分公司
        if (this.selectdata.state === '结束') {
          let http = new HttpResetClass()
          let res = await http.load('POST', 'rs/search', {
            source: 'this.getInfo()',
            userid: this.selectdata.userid
          }, {resolveMsg: null, rejectMsg: '处理人员获取失败！！！'})
          let user = res.data
          this.selectdata.operate_date = new Date(this.selectdata.finishtime).Format('yyyy-MM-dd')
          this.selectdata.operator = this.selectdata.person
          this.selectdata.orgs = user.orgs
          this.selectdata.parentname = user.deps
        }

        // 未结束且是下发查看指定人员
        if (this.selectdata.state !== '结束' && this.selectdata.actorexpression !== null && this.selectdata.actorexpression.indexOf('PI') === 0) {
          let http = new HttpResetClass()
          let res = await http.load('POST', 'rs/search', {
            source: 'this',
            userid: this.selectdata.actorexpression.substring(3, this.selectdata.actorexpression.length-1)
          }, {resolveMsg: null, rejectMsg: '处理人员获取失败！！！'})
          let user = res.data
          this.selectdata.operate_date = new Date().Format('yyyy-MM-dd')
          this.selectdata.operator = user.name
          this.selectdata.orgs = user.orgs
          this.selectdata.parentname = user.f_department_name
        }

        // 消除双向绑定，避免子组件（显示层）数据更改，父组件（控制层）也更改
        let temp = JSON.parse(JSON.stringify(this.selectdata))

        this.show_data = temp
        for (const item of this.show_data.fields) {
          if(item.label==='气价名称'){
            item.value=this.show_data.f_price_name
          }
        }
        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
          }
        }
      },
      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
          }
        }
      },
      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
          }
        }
      },
      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', 'rs/sql/apply_singleTable', {data: data}, {
          resolveMsg: null,
          rejectMsg: `${this.show_data.fields[index].label}查询失败`
        })
        if (res.data.length > 0) {
          this.show_data.fields[index].value = null
          this.$showAlert(`${this.show_data.fields[index].label}已存在！！！`, 'warning', 3000)
        }
      },
      // 获取片区
      async getSliceArea () {
        let data = {
          source: 'this.getParentByType($organization$).getAllChildrens().where(row.getType() == $zone$)',
          userid: this.$login.f.id
        }

        let res = await this.$resetpost(
          `rs/search`,
          {data: data},
          {resolveMsg: null, rejectMsg: '片区查询失败！！！'}
        )

        return res.data.map(item => {
          return {
            label: item.name,
            value: item.name
          }
        })
      },
      // 获取区县
      async getPcd () {
        let data = {
          tablename: 't_pcd',
          condition: `f_filialeid = '${this.$login.f.orgid}'`
        }
        let res = await this.$resetpost(
          `rs/sql/apply_singleTable`,
          {data: data},
          {resolveMsg: null, rejectMsg: '区县查询失败！！！'}
        )

        return res.data.map(item => {
          return {
            label: item.f_pcd,
            value: item.f_pcd
          }
        })
      },
      // 缴费前置
      chargeBefore () {
        if (Number(this.show_data.f_due_money) > Number(this.show_data.f_cumulative_payment_money) || Number(this.show_data.f_surplus_money) > 0) {
          this.$showAlert('费用未结清！！！', 'warning', 3000)
          throw null
        }
      },
      // 施工前置
      async constructionBefore () {
        let http = new HttpResetClass()
        let data = {
          condition: `ui.f_process_id = '${this.show_data.f_process_id}' and uf.f_table_state = '待开通'`
        }
        let res = await http.load(
          'POST',
          'rs/sql/countApplyUserinfo',
          {data: data},
          {
            resolveMsg: null,
            rejectMsg: '安装明细查询失败！！！'
          })
        if (res.data[0].num > 0) {
          this.$showAlert(`还有${res.data[0].num}户未安装，无法提交`, 'warning', 3000)
          throw `还有${res.data[0].num}户未安装，无法提交`
        }
      },
      changePipeBuild () {
        if (this.selectdata.f_process_dep === '工程部') {
          return 'this.getParentByType($organization$).getChildByName($工程部报装$).getChildren()'
        }
        if (this.selectdata.f_process_dep === '运营部') {
          return 'this.getParentByType($organization$).getChildByName($运营部报装$).getChildren()'
        }
      },
      async getDevInfo () {
        let data = {
          tablename: 't_dev_info',
          condition: `f_orgid = '${this.$login.f.orgid}'`
        }
        let res = await this.$resetpost(
          `rs/sql/apply_singleTable`,
          {data: data},
          {resolveMsg: null, rejectMsg: '公司查询失败！！！'}
        )

        return res.data.map(item => {
          return {
            label: item.f_dev_name,
            value: item.f_dev_name
          }
        })
      },
      async getPrice (f_price_id) {
       /* console.log('=======================')
        console.log(f_price_id)

        let data = {
          condition: `sp.f_orgid = '${this.$login.f.orgid}'`
        }

        if (!isEmpty(f_price_id)) {
          data.condition = `sp.f_orgid = '${this.$login.f.orgid}' and sp.f_price_id = ${f_price_id}`
        }
        let http = new HttpResetClass()
        let res = await http.load(
          'POST',
          `rs/sql/applyGetPrice`,
          {data: data},
          {resolveMsg: null, rejectMsg: '气价查询失败！！！'}
        )

        return res.data.map(item => {
          return {
            label: item.f_price_name,
            value: item
          }
        })*/
      },
      materialSupervisory () {
        if (this.selectdata.userid === this.$login.f.id) {
          return true
        }
        return false
      },
      async getDesignerPeople () {
        let data = {
          source: 'this.getParentByType($organization$).getChildByName($设计部报装$).getChildren()',
          userid: this.$login.f.id
        }

        let http = new HttpResetClass()
        let res = await http.load(
          'POST',
          `rs/search`,
          {data: data},
          {resolveMsg: null, rejectMsg: '设计人员查询失败！！！'}
        )

        return res.data.map(item => {
          return {
            label: item.name,
            value: item.id
          }
        })
      },
      // 获取区县
      async getArea () {
        let data = {
          tablename: 't_area',
          condition: `f_filialeid = '${this.$login.f.orgid}'`
        }
        let http = new HttpResetClass()
        let res = await http.load(
          'POST',
          `rs/sql/apply_singleTable`,
          {data: data},
          {resolveMsg: null, rejectMsg: '集收单位查询失败！！！'}
        )

        return res.data.map(item => {
          return {
            label: item.f_residential_area,
            value: item.f_residential_area
          }
        })
      }
    },
    events:{
      'complyInstallation' (index) {
      },
      // 选择材料
      async materialNameChenge (index, fieldIndex) {
        let material = this.show_data.onetomany[index].fields[fieldIndex].value

        this.show_data.onetomany[index].fields.forEach(item => {
          if (material[item.field]) {
            item.value = material[item.field]
          }
        })
      },
      // 打开模态框获取材料
      async 'getMaterialName' (index) {
        let data = {
          condition: `1=1`
        }
        let http = new HttpResetClass()
        let res = await http.load(
          'POST',
          `rs/sql/getStockMaterial`,
          {data: data},
          {resolveMsg: null, rejectMsg: '材料查询失败！！！'}
        )

        this.show_data.onetomany[index].fields.forEach(field => {
          if (field.label === '选择材料') {
            field.options = res.data.map(item => {
              return {
                'label': `${item.f_material_name}--${item.f_material_style}--${item.f_material_unit}`,
                'value': item
              }
            })
          }
        })
      },
      // 终止报建初始化·
      async 'stopApplyReadyEvent' () {

        let f_is_stop = this.getLableValue('是否终止')

        for (const item of this.show_data.fields) {
          if (f_is_stop === '是') {
            if (item.label === '终止原因') {
              item.hidden = false
              item.required = true
            }
          } else {
            if (item.label === '终止原因') {
              item.hidden = true
              item.required = false
            }
          }
        }

        if (isEmpty(this.show_data.f_parent_process_id)) {
          return
        }
        let data = {
          condition: `f_process_id = '${this.show_data.f_parent_process_id}'`,
          data: {
            id: this.$login.f.id,
            orgid: this.$login.f.orgid
          }
        }
        let res = await this.$resetpost(
          `rs/sql/supervisory`,
          {data: data},
          {resolveMsg: null, rejectMsg: '项目查询失败！！！'}
        )
        this.show_data.parentApply = res.data[0]
      },
      // 通气点火初始化
      async 'gasReadyEvent' () {
        /*if (!isEmpty(this.show_data.f_price_id)) {
          let priceList = await this.getPrice(this.show_data.f_price_id)
          this.setLabelValue('气价名称', priceList[0].value)
        }*/


        // 保险初始化显示内容
        let f_is_insure = this.getLableValue('是否购买保险')
        for (const item of this.show_data.fields) {
          if (f_is_insure === '是') {
            if (item.label === '保费开始日期' || item.label === '保费结束日期' || item.label === '险种' || item.label === '保费金额') {
              item.hidden = false
              item.required = true
            }
            if (item.label === '保险备注') {
              item.hidden = false
            }
          } else {
            if (item.label === '保费开始日期' || item.label === '保费结束日期' || item.label === '险种' || item.label === '保费金额') {
              item.hidden = true
              item.required = false
            }
            if (item.label === '保险备注') {
              item.hidden = true
            }
          }
        }
      },
      // 申请节点初始化
      'applyReadyEvent' () {
        this.$getConfig(this, 'UserAddress')

        let f_address_type = this.show_data.f_address_type

        for (const item of this.show_data.fields) {
          if (f_address_type === '民用市区') {
            if (item.label === '区/县' || item.label === '街道/乡镇' || item.label === '集收单位' || item.label === '门牌号') {
              item.hidden = false
              item.required = true
            }
            if (item.label === '楼号/组' || item.label === '单元/排' || item.label === '楼层') {
              item.hidden = false
              item.required = false
            }
            if (item.label === '地址') {
              item.readonly = true
            }
          }
          if (f_address_type === '民用乡镇') {
            if (item.label === '区/县' || item.label === '街道/乡镇' || item.label === '集收单位' || item.label === '门牌号') {
              item.hidden = false
              item.required = true
            }
            if (item.label === '楼号/组' || item.label === '单元/排' || item.label === '楼层') {
              item.hidden = false
              item.required = false
            }
            if (item.label === '楼层') {
              item.hidden = true
              item.required = false
            }
            if (item.label === '地址') {
              item.readonly = true
            }
          }
          if (f_address_type === '特殊地址') {
            if (item.label === '区/县' || item.label === '街道/乡镇') {
              item.hidden = false
              item.required = true
            }
            if (item.label === '集收单位') {
              item.hidden = false
              item.required = false
            }
            if (item.label === '楼号/组' || item.label === '单元/排' || item.label === '楼层' || item.label === '门牌号') {
              item.hidden = true
              item.required = false
            }
            if (item.label === '地址') {
              item.readonly = false
            }
          }

          if (this.show_data.f_apply_source === '线下发起' && item.label === '预约地址') {
            item.hidden = true
          }
        }
      },
      // 失去焦点出触发事件
      'onchange' (index) {
        if (this.show_data.defname === '报装申请' || this.show_data.defname === '信息确认') {
          if (
            this.show_data.fields[index].label === '区/县' ||
            this.show_data.fields[index].label === '街道/乡镇' ||
            this.show_data.fields[index].label === '集收单位' ||
            this.show_data.fields[index].label === '楼号/组' ||
            this.show_data.fields[index].label === '单元/排' ||
            this.show_data.fields[index].label === '楼层' ||
            this.show_data.fields[index].label === '门牌号'
          ) {

            let f_pcd = this.getLableValue('区/县') || ''
            let f_street = this.getLableValue('街道/乡镇') || ''
            let f_residential_area = this.getLableValue('集收单位') || ''
            let f_building = this.getLableValue('楼号/组') || ''
            let f_building_suffix = f_building ? this.config.f_building_suffix : ''
            let f_unit = this.getLableValue('单元/排') || ''
            let f_unit_suffix = f_unit ? this.config.f_unit_suffix : ''
            let f_floor = this.getLableValue('楼层') || ''
            let f_floor_suffix = f_floor ? this.config.f_floor_suffix : ''
            let f_room = this.getLableValue('门牌号') || ''
            let f_room_suffix = f_room ? this.config.f_room_suffix : ''

            let f_address = f_pcd + f_street + f_residential_area + f_building + f_building_suffix + f_unit + f_unit_suffix + f_floor + f_floor_suffix + f_room + f_room_suffix
            this.setLabelValue("地址", f_address)
          }
        }
      },
      // =============================
      selectSearch (val, index) {},
      'onblur' (index) {},
      'oninput' (index) {},
      'initializtionView' () {},
      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',
          `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(
          'rs/entity/t_apply',
          this.show_data
        )

        this.$dispatch('breakControl', this.show_data)
      },
      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(
          `rs/entity/${this.show_data.onetomany[index].tables[0]}`,
          data
        )

        res = await this.$resetpost(
          'rs/entity/t_apply',
          this.show_data
        )

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

        res = await this.$resetpost(
          'rs/entity/t_apply',
          this.show_data
        )

        this.$dispatch('breakControl', this.show_data)
      },
      async 'importEvent' (index, table, configName, filepath) {
        let data = {
          selectdata: this.show_data,
          table: table,
          filepath: filepath,
          configName: configName,
          user: this.$login.f
        }

        let res = await this.$resetpost(
          `rs/logic/importEvent`,
          data
        )

        this.$dispatch('breakControl', this.show_data)
      },
      'onbutchange' (index) {

      },
      'onbutblur' (index) {

      },
      'onbutinput' (index) {

      }
    },
    watch: {
      deep: true
    }
  }
</script>
<style scoped>
  /*清除model中的浮动*/
  .clearfix:after,.clearfix:before{
    display: table;
  }
  .clearfix:after{
    clear: both;
  }
</style>
