<template>
  <button class="button_search button_spacing" @click="watchshowChange()">扎帐</button>
  <button class="button_search button_spacing" @click="history()">历史记录</button>

  <modal :show.sync="isHistory" v-ref:modal backdrop="false">
    <header slot="modal-header" class="modal-header text-center">
      <h4 class="modal-title"><span>历史记录</span><button style="margin-left: 90%;border-width: 0px;" @click="isHistory=!isHistory">×</button></h4>
    </header>
    <article slot="modal-body">
      <data-grid :model="models" partial='list' class="basic-main list_area table_sy" v-ref:grid>
        <template partial='head'>
          <tr>
            <th>
              <nobr>报表名称</nobr>
            </th>
            <th>
              <nobr>扎帐金额</nobr>
            </th>
            <th>
              <nobr>系统金额</nobr>
            </th>
            <th>
              <nobr>扎帐归属时间</nobr>
            </th>
            <th>
              <nobr>操作时间</nobr>
            </th>
            <th>
              <nobr>状态</nobr>
            </th>
            <th>
              <nobr>操作员</nobr>
            </th>
            <th>
              <nobr>备注</nobr>
            </th>
            <th>
              <nobr>操作</nobr>
            </th>
          </tr>
        </template>
        <template partial='body'>
          <td style="text-align: center;">
            <nobr>{{row.f_report_name}}</nobr>
          </td>
          <td style="text-align: center;">
            <nobr>{{row.f_fee}}</nobr>
          </td>
          <td style="text-align: center;">
            <nobr>{{row.f_report_fee}}</nobr>
          </td>
          <td style="text-align: center;">
            <nobr>{{row.f_end_date}}</nobr>
          </td>
          <td style="text-align: center;">
            <nobr>{{row.f_operate_date}}</nobr>
          </td>

          <td style="text-align: center;">
            <nobr>{{row.f_state}}</nobr>
          </td>
          <td style="text-align: center;">
            <nobr>{{row.f_operator}}</nobr>
          </td>
          <td style="text-align: center;">
            <nobr>{{row.f_remarks}}</nobr>
          </td>
          <td style="text-align: center;">
            <button v-if="row.f_operate_state == 1" class="button_search button_spacing" @click="$parent.$parent.$parent.repeal(row)">撤销</button>
          </td>
        </template>
      </data-grid>
    </article>
    <footer slot="modal-footer" class="modal-footer"></footer>
  </modal>
  <modal :show.sync="specialCircumstances && watchshow" v-ref:modal backdrop="false">
    <header slot="modal-header" class="modal-header text-center">
      <h4 class="modal-title">扎帐选择</h4>
      <input type="checkbox" class="" id="f_generations" :checked="fields.length === tieData.length" @click='checkedAll()' >
      <label for="f_generations" class="font-size">全选</label>
    </header>
    <article slot="modal-body">
      <div class="auto col-sm-11 col-md-offset-1"  style="margin-top: 10px;">
        <div class="col-sm-3" v-for="(index, item) in tieData">
          <input type='checkbox' :id="'water-owe-details-'+index" :checked="fields.indexOf(item.name)>=0" name='checkboxinput' class='input-checkbox' @click='checkedOne(item.name)'>
          <label :for="'water-owe-details-'+index" class="font-size">{{item.name}}</label>
        </div>
      </div>
    </article>
    <footer slot="modal-footer" class="modal-footer">
      <center>
        <button type="button" class="btn btn-default" @click='watchshow = !watchshow'>取消</button>
        <button type="button" class="btn btn-success" @click='watchshowChange(1)'>确认</button>
      </center>
    </footer>
  </modal>

  <modal :show.sync="isTieModal"  v-ref:modal large backdrop="false">
    <header slot="modal-header" class="modal-header">
      <h3 style="color:black" class="modal-title">请确认扎帐金额</h3>
    </header>
    <article slot="modal-body" class="modal-body">
      <validator name='v'>
        <form class="form-horizontal  select-overspread">
          <div class="row">
            <div v-for="(key, value) in org" v-if ="value.trim()!=''" class="col-sm-4 form-group">
              <label class="font_normal_body">{{ key == 'f_orgname' ? '&emsp;&emsp;&emsp;&emsp;公司' : key == 'f_depname' ? '&emsp;&emsp;&emsp;&emsp;部门' : '&emsp;&emsp;&emsp;&emsp;人员' }}</label>
              <input type="text" style="width:60%" class="input_search" :value="value"
                     disabled="disabled">
            </div>
          </div>
          <div class="row">
            <div class="col-sm-4 form-group" v-for="item in affirmDate">
              <label class="font_normal_body">&emsp;&emsp;&emsp;&emsp;{{item.name}}</label>
              <input type="text" style="width:60%" class="input_search" :value="item.val"
                     disabled="disabled">
            </div>
            <div class="col-sm-4 form-group" >
              <label class="font_normal_body" for="startDate">上次扎帐日期</label>
              <datepicker id="startDate" placeholder="上次扎帐日期" style="width: 60%"
                          v-model="startDate"
                          :value.sync="startDate"
                          :disabled-days-of-Week="[]"
                          :format="'yyyy-MM-dd HH:mm:ss'"
                          :disabled="true"
                          :show-reset-button="reset">
              </datepicker>
            </div>
            <div class="col-sm-4 form-group" >
              <label class="font_normal_body" for="endDate">本次扎帐日期</label>
              <datepicker id="endDate" placeholder="本次扎帐日期" style="width: 60%"
                          v-model="endDate"
                          :value.sync="endDate"
                          :disabled-days-of-Week="[]"
                          :format="'yyyy-MM-dd HH:mm:ss'"
                          :disabled="true"
                          :show-reset-button="reset">
              </datepicker>
            </div>
          </div>
          <div class="row">
            <div class="col-sm-4 form-group" >
              <label class="font_normal_body">&emsp;系统总金额</label>
              <input type="text" style="width:60%" class="input_search" v-model="reportstr"
                     disabled="disabled" placeholder="系统金额">
            </div>
            <div class="col-sm-4 form-group" >
              <label class="font_normal_body">&emsp;扎帐总金额</label>
              <input type="text" style="width:60%" class="input_search" v-model="f_fee"
                     placeholder="扎帐金额">
            </div>
          </div>
          <div class="row">
            <div class="col-sm-11 form-group">
              <label class="font_normal_body"><nobr>&emsp;&emsp;&emsp;&emsp;备注</nobr></label>
              <textarea style="resize:none;width:95%;" class="input_search"
                        v-model='f_remarks' ></textarea>
            </div>
          </div>
        </form>
      </validator>
    </article>
    <footer slot="modal-footer" class="modal-footer">
      <button class="btn btn-success" @click="searchData">确认扎帐</button>
      <button class="btn btn-default" @click="isTieModal = !isTieModal">取消</button>
    </footer>
  </modal>
</template>

<script>
import {DataModel, HttpResetClass, PagedList} from "vue-client"

let valdef = async function (self) {
  // 读取扎帐配置
  await self.$getConfig(self, 'TieConfig')
  if (self.defaultfield) {
    self.fields = [...self.defaultfield]
  }
  self.getStartDate ()
  console.log('扎帐配置信息', self.config)
}
export default {
  title: '扎帐组件',
  props: {
    model: {},
    endDate: '',
    // 扎帐金额
    reportFee: {
      default: ''
    },
    // 带有特殊标记的扎帐金额字符串
    feeStr: {
      default: '#()'
    },
    // 特殊情况
    specialCircumstances: false,
    // 筛选出标记的扎帐金额正则表达式 默认 #()
    regex: {
      default: /#(.+?)\)/g
    },
    // 报表所选 公司 部门 人员 {f_orgname,f_depname,f_operator}
    org: {},
    // 筛选出标记的扎帐金额所对应的列名正则表达式 默认 ^()
    titRegex: {
      default: /\^(.+?)\)/g
    },
    // 删掉掉标记的正则表达式
    rep: {
      default: /\[|\]|&|@|!|#|%|\{|\}|\(|\)|\$|\^/g
    },

    // 默认列
    defaultfield: []
  },
  data () {
    return {
      config: {
        // // 配置需要扎帐公司部门 如需全部扎帐 orgname: '*',
        // isOrgname: true, // true表示不能跨公司
        // isDepname: true, // true表示不能跨部门
        // isUser: true, // true表示不能跨人员
        // orgname: ['巩义市燃气有限公司'],
        // depname: ['嵩山路营业厅', '人民路营业厅']
      },
      // 上次扎帐日期
      startDate: '',
      models: {rows:[]},
      watchshow: false,
      isTieModal: false,
      f_orgid: this.$login.f.orgid,
      f_orgname: this.$login.f.orgs,
      f_depid: this.$login.f.depids,
      f_depname: this.$login.f.deps,
      f_operator_id: this.$login.f.id,
      f_operator: this.$login.f.name,
      f_remarks: '',
      reportstr: '',
      isHistory: false,
      f_fee: '',
      // 扎帐数据 [{name: xxx,val: xxx}]
      tieData: [],
      condition: '',
      fields: [],
      isCheckedAll: false,
      affirmDate: []
    }
  },
  ready () {
    console.log('加载扎帐组件')
    valdef(this)
  },
  methods: {
    async getStartDate () {
      // 获取上次扎帐日期
      let condition = `f_report_path='${this.model.f_report_path}' and f_state = '有效'`
      if (this.config.isOrgname) {
        condition += ' and f_orgid = ' + this.f_orgid
      }
      if (this.config.isDepname) {
        condition += ` and  f_depid = '${this.f_depid}'`
      }
      if (this.config.isUser) {
        condition += ' and f_operator_id = ' + this.f_operator_id
      }
      this.condition = condition
      let querys= await this.$resetpost('api/af-revenue/sql/PrickBillQuery?pageNo=1&pageSize=7',
          {data:{condition:condition}},{resolveMsg:null,rejectMsg:'查询出错'})
      this.models.rows = querys.data
      if (querys.data.length === 0){
        this.$dispatch('update', '')
      }
    },
    history() {
      this.isHistory = !this.isHistory
      this.getStartDate()
    },
    repeal(val){
      console.log('撤销信息', val)
      let data = {
        flag: 2,
        f_orgid: this.$login.f.orgid,
        f_orgname: this.$login.f.orgs,
        f_depid: this.$login.f.depids,
        f_depname: this.$login.f.deps,
        f_operator_id: this.$login.f.id,
        f_operator: this.$login.f.name,
        data: {
          id: val.id,
          f_state: '无效'
        }
      }
      if(this.$login.r.includes('扎帐撤销权限')) {
        data.flag = 3
      }
      this.$resetpost('rs/logic/SaveTieAnAccount',
        {data:data},
        {resolveMsg:null,rejectMsg:null}).then(res =>{
        switch (res.data) {
          case 202 :
              this.$showAlert('撤销成功', 'success', 3000)
              this.getStartDate()
              this.isHistory = !this.isHistory
            break
          case 201 : this.$showAlert('撤销失败,该条记录不是当天扎帐记录，不能撤销！', 'warning', 3000)
            break
        }
      })
    },
    watchshowChange (val) {
      if (val) {
        if (!this.fields[0]) return
        this.getStartDate()
        this.isTieModal = true
        this.watchshow = false
        this.f_fee = this.reportstr = this.sumMoney(this.tieData, this.fields)
        return
      }
      // 判断是否配置需扎帐的公司
      if (JSON.stringify(this.config) === '{}') {
        this.$showAlert(`未配置扎帐信息TieConfig.json 例:
                  {
                    isOrgname: true, // true表示不能跨公司
                    isDepname: true, // true表示不能跨部门
                    isUser: true, // true表示不能跨人员
                    orgname: ['公司名',...], // '*' 表示全部
                    depname: ['部门名',...] // '*' 表示全部
                  }`, 'warning', 4000)
        return
      }
      // 判断报表是否有数据
      if ((this.feeStr == null || this.feeStr === '#()') && this.reportFee === '') {
        this.$showAlert('未查询数据', 'warning', 4000)
        return
      }
      // 判断 是否是扎帐公司
      if (this.config.orgname !== '*' && !this.config.orgname.includes(this.f_orgname)) {
        this.$showAlert('禁止扎帐 账号所属分公司无需扎帐', 'warning', 4000)
        return
      }
      // 判断 是否是扎帐部门
      if (this.config.depname !== '*' && !this.config.depname.includes(this.f_depname)) {
        this.$showAlert('禁止扎帐 账号所属部门无需扎帐', 'warning', 4000)
        return
      }
      // 本公司只能扎本公司的
      if (this.config.isOrgname && this.f_orgname !== this.org.f_orgname) {
        console.log('本公司只能扎本公司的', this.config.isOrgname, this.f_orgname, this.org.f_orgname[0])
        this.$showAlert('禁止跨分公司扎帐', 'warning', 4000)
        return
      }
      // 本部门只能扎本部门的
      if (this.config.isDepname && this.f_depname !== this.org.f_depname) {
        console.log('本公司只能扎本部门的', this.config.isDepname, this.f_depname, this.org.f_depname[0])
        this.$showAlert('禁止跨部门扎帐', 'warning', 4000)
        return
      }
      // 本人只能扎本人的
      if (this.config.isUser && this.f_operator !== this.org.f_operator) {
        this.$showAlert('请选择人员 \"' + this.f_operator + '\"进行扎帐', 'warning', 4000)
        return
      }
      this.$dispatch('special', this)

      if (this.specialCircumstances) {
        this.watchshow = true
      } else {
        this.isTieModal = true
      }

    },
    getBracketStr (val) {
      let item = []
      if (this.reportFee != '') {
        item.push({name: '总金额', val: this.reportFee})
        return
      }
      if (val == null || val == '') {
        item.push({name: '总金额', val: 0})
        return
      }
      let regex = this.regex
      let rep = this.rep
      let moneys = val.toString().match(regex)
      let titles = val.toString().match(this.titRegex)
      if (titles && titles.length > 0) {
        for (let i = 0; i < titles.length; i++) {
          let name = titles[i].toString().replace(rep, '').trim()
          let value = moneys[i].toString().replace(rep, '').trim()
          item.push({name: name, val: value})
        }
      }
      this.tieData = item
    },
    sumMoney (obj, conf) {
      this.affirmDate = obj.filter(x => conf.includes(x.name))
      let option = obj.filter(x => conf.includes(x.name)).map(x => parseFloat(x.val)).reduce((x, y) => x + y, 0)
      return option.toFixed(2)
    },

    searchData () {
      if (parseFloat(this.reportstr) != parseFloat(this.f_fee)) {
        this.$showAlert('扎帐金额有误，无法保存', 'warning', 3000)
        return
      }
      let condition = ''

      for (let [key,val] of Object.entries(this.org)) {
        condition += val + '.'
      }
      let info = {
        saveData: [],
        condition: this.condition,
        flag: '1' // 1表示保存
      }
      for (let rs of this.affirmDate) {
        let xx = {
          f_report_name: this.model.f_report_name,
          f_report_path: this.model.f_report_path,
          f_report_type: this.model.f_report_type,
          f_report_fee: rs.val,
          f_fee: rs.val,
          f_state: '有效',
          f_end_date: this.endDate,
          startDate: this.startDate,
          f_orgid: this.f_orgid,
          f_orgname: this.f_orgname,
          f_depid: this.f_depid,
          f_depname: this.f_depname,
          f_operator_id: this.f_operator_id,
          f_operator: this.f_operator,
          f_remarks: this.f_remarks,
          f_condition: condition + rs.name
        }
        info.saveData.push(xx)
      }
      let HttpReset = new HttpResetClass()
      HttpReset.load('POST', 'rs/logic/SaveTieAnAccount', info,
        {resolveMsg: null, rejectMsg: null}).then((res) => {
        switch (res.data) {
          case 200 :
            this.$showAlert('保存成功', 'success', 3000)
            this.getStartDate()
            break
          case 201 : this.$showAlert('重复扎帐', 'warning', 3000)
            break
        }
        this.watchshow = false
        this.isTieModal = false
      })
    },
    checkedOne (name) {
      let nameIndex = this.fields.indexOf(name)
      if (nameIndex >= 0) {
        // 如果已经包含, 则去除(单选按钮由选中变为非选中状态)
        this.fields.splice(nameIndex, 1)
      } else {
        // 选中该checkbox
        this.fields.push(name)
        if (this.fields.length === this.tieData.length) {
          this.isCheckedAll = true
        } else {
          this.isCheckedAll = false
        }
      }
    },
    checkedAll () {
      this.isCheckedAll = !this.isCheckedAll
      if (this.isCheckedAll) {
        // 全选时
        this.fields = this.tieData.map(n => n.name)
      } else {
        this.fields = []
      }
    }
  },
  watch: {
    'fields' (val) {
      this.f_fee = this.reportstr = this.sumMoney(this.tieData, val)
    },
    'getOrg' (val) {
      console.log("org========> ", val )
    },
    'feeStr' (val) {
      this.getBracketStr(val)
      if(!this.specialCircumstances) {
        this.fields = this.tieData.map(x => x.name)
      }
    },
    'models.rows' (val) {
      if (val && val.length > 0) {
        this.startDate = val.map(x => x.f_end_date)[0].toString() // 获取 上次扎帐时间
        console.log('opopopopopo:', this.startDate)
        this.$dispatch('update', this.startDate)
      }
    }
  },
  computed: {

  }
}
</script>

<style scoped>

</style>


