<template>
  <div>
    <el-form size="middle" :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="formReadOnly"
             label-width="100px" @submit.native.prevent>

      <el-divider content-position="left"><i class="el-icon-document"></i> 基础信息</el-divider>
      <el-row :gutter="26">
        <el-col :span="12">
          <el-form-item label="经办人" prop="userName">
            <el-input v-model="inputForm.userName" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="报销编号" prop="no">
            <el-input v-model="inputForm.no" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属部门" prop="department">
            <el-input v-model="inputForm.department" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="报销日期" prop="reimDate" :rules="[{required: true, message:'请选择报销日期', trigger:'blur'}]">
            <el-date-picker
              v-model="inputForm.reimDate"
              type="date"
              value-format="yyyy-MM-dd"
              style="width: 100%"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="inputForm.remarks"
                      type="textarea"
                      :rows="5"
                      maxlength="500"
                      placeholder="请输入简介"
                      show-word-limit>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left"><i class="el-icon-document"></i>
        报销详情
        <el-button style="margin-left: 20px" type="primary" :disabled="method==='view' || this.formReadOnly" size="mini" @click="insertEvent('detail')" plain>
          新增
        </el-button>
      </el-divider>
      <el-row  :gutter="15" >
        <vxe-table
          border
          show-footer
          show-overflow
          :footer-method="footerMethod"
          ref="detailTable"
          class="vxe-table-element"
          :data="inputForm.detailInfos"
          style="margin-left: 5em"
          @cell-click=""
          @edit-closed=""
          highlight-current-row
          :edit-config="{trigger: 'click', mode: 'cell', showStatus: true, autoClear: true}"
        >
          <vxe-table-column field="userName" title="报销人" :edit-render="{}" :rules="[{required: true, message:'请选择报销人', trigger:'blur'}]">
            <template v-slot:edit="scope">
              <el-input v-model="scope.row.userName" @focus="userPullListForm(scope.$rowIndex)"></el-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="deptName" title="报销部门" :edit-render="{}">
            <template v-slot:edit="scope">
              <el-input :disabled='true' v-model="scope.row.deptName" ></el-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="typeName" title="报销类型" :edit-render="{}" :rules="[{required: true, message:'请选择报销类型', trigger:'blur'}]">
            <template v-slot:edit="scope">
              <el-input v-model="scope.row.typeName" @focus="typePullForm(scope.$rowIndex)"></el-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="projectName" title="报销项目" :edit-render="{}" :rules="[{required: true, message:'请选择报销项目', trigger:'blur'}]">
            <template v-slot:edit="scope">
              <el-input v-model="scope.row.projectName" @focus="openProgramPageForm(scope.$rowIndex, scope.row)"></el-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="reportNumber" title="报告号" :edit-render="{}">
            <template v-slot:edit="scope">
              <el-input :disabled="true" v-model="scope.row.reportNumber" ></el-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="number" title="费用(元)" :edit-render="{}" :rules="[{required: true, message:'请输入费用', trigger:'blur'}]">
            <template v-slot:edit="scope">
              <el-input maxlength="15" v-model="scope.row.number" @keyup.native="scope.row.number = twoDecimalPlaces(scope.row.number)"></el-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="receiptNumber" title="收据张数" :edit-render="{}">
            <template v-slot:edit="scope">
              <el-input v-model="scope.row.receiptNumber" oninput ="value=value.replace(/\D|^0/g,'')" maxlength="10"></el-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="days" title="出差天数" :edit-render="{}">
            <template v-slot:edit="scope">
              <el-input v-model="scope.row.days" oninput ="value=value.replace(/\D|^0/g,'')" maxlength="10"></el-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="content" title="内容" :edit-render="{}">
            <template v-slot:edit="scope">
              <el-input v-model="scope.row.content" ></el-input>
            </template>
          </vxe-table-column>
          <vxe-table-column title="操作" width="100">
            <template v-slot="scope">
              <el-button size="mini" type="danger" @click="removeEvent(scope.row,scope.$rowIndex,'detail')">删除</el-button>
            </template>
          </vxe-table-column>
        </vxe-table>
      </el-row>

      <el-divider content-position="left"><i class="el-icon-document"></i>
        专用发票信息
        <el-button style="margin-left: 20px" type="primary" :disabled="method==='view' || this.formReadOnly " size="mini" @click="insertEvent('amount')" plain>
          新增
        </el-button>
      </el-divider>
      <el-row  :gutter="15" >
        <vxe-table
          border
          show-overflow
          ref="amountTable"
          class="vxe-table-element"
          :data="inputForm.amountInfos"
          style="margin-left: 5em"
          @cell-click=""
          @edit-closed=""
          highlight-current-row
          :edit-config="{trigger: 'click', mode: 'cell', showStatus: true, autoClear: true}"
        >
          <vxe-table-column field="code" title="发票代码" :edit-render="{}">
            <template v-slot:edit="scope">
              <el-input oninput ="value=value.replace(/\D|^0/g,'')" maxlength="10" v-model="scope.row.code" ></el-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="number" title="发票号" :edit-render="{}">
            <template v-slot:edit="scope">
              <el-input oninput ="value=value.replace(/\D|^0/g,'')" maxlength="8" @change="isExict(scope.row)" v-model="scope.row.number" ></el-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="amount" title="金额" :edit-render="{}">
            <template v-slot:edit="scope">
              <el-input maxlength="15" v-model="scope.row.amount" @keyup.native="scope.row.amount = twoDecimalPlaces(scope.row.amount)" @change="countAmount(scope.row)"></el-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="taxAmount" title="税额" :edit-render="{}">
            <template v-slot:edit="scope">
              <el-input maxlength="15" v-model="scope.row.taxAmount" @keyup.native="scope.row.taxAmount = twoDecimalPlaces(scope.row.taxAmount)" @change="countAmount(scope.row)"></el-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="count" title="价税合计" :edit-render="{}">
            <template v-slot:edit="scope">
              <el-input disabled="true" v-model="scope.row.count" ></el-input>
            </template>
          </vxe-table-column>
          <vxe-table-column title="操作" width="100">
            <template v-slot="scope">
              <el-button size="mini" type="danger" @click="removeEvent(scope.row,scope.$rowIndex,'amount')">删除</el-button>
            </template>
          </vxe-table-column>
        </vxe-table>
      </el-row>

      <!-- 附件 -->
      <UpLoadComponent ref="uploadComponent"></UpLoadComponent>
      <ProgramPageForm ref="programPageForm" @getProgram="getProgram"></ProgramPageForm>
      <ReimbursementTypePullForm ref="reimbursementTypePullForm" @getProgramForType="getProgramForType"></ReimbursementTypePullForm>
      <UserPullForm ref="userPullForm" @getProgramForUser="getProgramForUser"></UserPullForm>
    </el-form>
  </div>
</template>

<script>
  import ReimbursementService from '@/api/sys/ReimbursementService'
  import ReimbursementTypeService from '@/api/sys/ReimbursementTypeService'
  import UpLoadComponent from '@/views/common/UpLoadComponent'
  import SelectUserTree from '@/views/modules/utils/treeUserSelect'
  import SelectTree from '@/components/treeSelect/treeSelect.vue'
  import XEUtils from 'xe-utils'
  import UserService from '@/api/sys/UserService'
  import ProgramPageForm from '@/views/modules/finance/invoice/ProgramPageForm'
  import ReimbursementTypePullForm from '@/views/modules/finance/invoice/ReimbursementTypePullForm'
  import UserPullForm from '@/views/modules/finance/invoice/UserPullForm'
  export default {
    data () {
      return {
        title: '',
        method: '',
        visible: false,
        loading: false,
        indexRow: '',
        inputForm: {
          userId: '',
          userName: '',
          no: '',
          department: '',
          reimDate: '',
          remarks: '',
          detailInfos: [],
          amountInfos: [],
          files: [] // 附件信息
        }
      }
    },
    reimbursementService: null,
    reimbursementTypeService: null,
    userService: null,
    created () {
      this.reimbursementService = new ReimbursementService()
      this.inputForm.userId = this.userId
      this.inputForm.userName = this.name
      this.inputForm.reimDate = new Date()
      this.inputForm.department = this.officeName
      this.userService = new UserService()
      this.reimbursementTypeService = new ReimbursementTypeService()
    },
    props: {
      businessId: {
        type: String,
        default: ''
      },
      formReadOnly: {
        type: Boolean,
        default: false
      }
    },
    components: {
      UpLoadComponent,
      SelectUserTree,
      SelectTree,
      ProgramPageForm,
      ReimbursementTypePullForm,
      UserPullForm
    },
    computed: {
      name () {
        return JSON.parse(localStorage.getItem('user')).name
      },
      officeName () {
        return JSON.parse(localStorage.getItem('user')).officeDTO.name
      },
      userId () {
        return JSON.parse(localStorage.getItem('user')).id
      }
    },
    watch: {
      'businessId': {
        handler (newVal) {
          console.log('aaaaaaaaaaaaaaaaaaaaaaaaaa', this.businessId)
          if (this.businessId && this.businessId !== 'false') {
            this.init('edit', this.businessId)
          } else {
            this.init('clean', '')
          }
        },
        immediate: true,
        deep: false
      }
    },
    methods: {
      init (method, id) {
        this.method = method
        this.inputForm = {
          userName: '',
          no: '',
          department: '',
          reimDate: '',
          remarks: '',
          detailInfos: [],
          amountInfos: [],
          files: [] // 附件信息
        }
        if (method === 'add') {
          this.title = `新建报销类型`
        } else if (method === 'edit') {
          this.inputForm.id = id
          this.title = '修改报销类型'
        }
        this.visible = true
        this.loading = false
        this.$nextTick(() => {
          if (this.formReadOnly === true && this.businessId !== 'false') {
            method = 'view'
          }
          if (method === 'edit' || method === 'view') { // 修改或者查看
            this.loading = true
            this.$refs.inputForm.resetFields()
            this.reimbursementService.findById(this.inputForm.id).then(({data}) => {
              this.inputForm = this.recover(this.inputForm, data)
              this.$refs.uploadComponent.newUpload(method, this.inputForm.files, 'reimbursement')
              this.inputForm = JSON.parse(JSON.stringify(this.inputForm))
              this.loading = false
            })
          }
          if (method !== 'edit' && method !== 'view') {
            this.$refs.uploadComponent.newUpload(method, [], 'reimbursement')
          }
        })
      },
      // 表单提交
      doSubmit () {
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            if (this.$refs.uploadComponent.checkProgress()) {
              this.loading = false
              return
            }
            if (this.commonJS.isEmpty(this.inputForm.files)) {
              this.inputForm.files = []
            }
            this.inputForm.id = this.businessId
            this.inputForm.files = this.$refs.uploadComponent.getDataList()
            this.reimbursementService.save(this.inputForm).then(({data}) => {
              this.close()
              this.$message.success(data)
              this.$emit('refreshDataList')
              this.loading = false
            }).catch(() => {
              this.loading = false
            })
          }
        })
      },
      close () {
        this.$refs.inputForm.resetFields()
        this.inputForm.detailInfos = []
        this.inputForm.amountInfos = []
        this.$refs.uploadComponent.clearUpload()
        this.visible = false
      },
      // 删除
      removeEvent (row, rowIndex, type) {
        if (type === 'detail') {
          this.$refs.detailTable.remove(row)
          this.inputForm.detailInfos.splice(rowIndex, 1)
        }
        if (type === 'amount') {
          this.$refs.amountTable.remove(row)
          this.inputForm.amountInfos.splice(rowIndex, 1)
        }
      },
      // 新增
      async insertEvent (type) {
        if (type === 'detail') {
          await this.$refs.detailTable.insert().then((data) => {
            data.userName = this.name
            data.deptName = this.officeName
            this.inputForm.detailInfos.push(data)
          })
        }
        if (type === 'amount') {
          await this.$refs.amountTable.insert().then((data) => {
            this.inputForm.amountInfos.push(data)
          })
        }
      },
      // 暂存
      async saveForm (callback) {
        this.loading = true
        if (this.$refs.uploadComponent.checkProgress()) {
          this.loading = false
          return
        }
        if (this.commonJS.isEmpty(this.inputForm.files)) {
          this.inputForm.files = []
        }
        this.inputForm.files = this.$refs.uploadComponent.getDataList()
        this.inputForm.type = '1'
        this.reimbursementService.save(this.inputForm).then(({data}) => {
          callback()
          this.$refs.inputForm.resetFields()
          this.loading = false
        }).catch(() => {
          this.$refs.inputForm.resetFields()
          this.loading = false
        })
      },
      // 送审
      async startForm (callback) {
        this.$refs['inputForm'].validate(async (valid) => {
          if (valid) {
            this.loading = true
            if (this.$refs.uploadComponent.checkProgress()) {
              this.loading = false
              return
            }
            if (this.commonJS.isEmpty(this.inputForm.files)) {
              this.inputForm.files = []
            }
            if (this.commonJS.isEmpty(this.inputForm.detailInfos)) {
              this.$message.error('至少填写一条报销详情信息')
              this.loading = false
              return
            } else {
              let i = this.inputForm.detailInfos.length
              for (let j = 0; j < i; j++) {
                let k = j + 1
                if (this.commonJS.isEmpty(this.inputForm.detailInfos[j].userName)) {
                  this.$message.error('报销详情第' + k + '行请选择报销人')
                  this.loading = false
                  return
                }
                if (this.commonJS.isEmpty(this.inputForm.detailInfos[j].typeName)) {
                  this.$message.error('报销详情第' + k + '行请选择报销类型')
                  this.loading = false
                  return
                }
                if (this.commonJS.isEmpty(this.inputForm.detailInfos[j].projectName)) {
                  this.$message.error('报销详情第' + k + '行请选择报销项目')
                  this.loading = false
                  return
                }
                if (this.commonJS.isEmpty(this.inputForm.detailInfos[j].number)) {
                  this.$message.error('报销详情第' + k + '行请输入费用')
                  this.loading = false
                  return
                }
              }
            }
            // if (this.commonJS.isEmpty(this.inputForm.amountInfos)) {
            //   this.$message.error('至少填写一条专用发票信息')
            //   this.loading = false
            //   return
            // }
            this.inputForm.files = this.$refs.uploadComponent.getDataList()
            this.inputForm.type = '2'
            this.reimbursementService.save(this.inputForm).then(({data}) => {
              callback(data.businessTable, data.businessId, this.inputForm)
              this.$refs.inputForm.resetFields()
              this.loading = false
            }).catch(() => {
              this.$refs.inputForm.resetFields()
              this.loading = false
            })
          }
        })
      },
      // 通过
      async agreeForm (callback) {
        this.$refs['inputForm'].validate(async (valid) => {
          if (valid) {
            this.loading = true
            if (this.$refs.uploadComponent.checkProgress()) {
              this.loading = false
              return
            }
            if (this.commonJS.isEmpty(this.inputForm.files)) {
              this.inputForm.files = []
            }
            this.inputForm.files = this.$refs.uploadComponent.getDataList()
            await this.userService.is().then(({data}) => {
              if (data) {
                this.inputForm.type = '5'
              }
            })
            this.reimbursementService.save(this.inputForm).then(({data}) => {
              callback(data.businessTable, data.businessId, this.inputForm)
              this.loading = false
            }).catch(() => {
              this.loading = false
            })
          }
        })
      },
      // 修改状态
      updateStatusById (type) {
        if (type === 'reject') {
          this.inputForm.type = '4'
          this.reimbursementService.updateStatusById(this.inputForm)
        }
      },
      footerMethod ({ columns, data }) {
        const footerData = [
          columns.map((column, columnIndex) => {
            if (columnIndex === 0) {
              return '总报销费用'
            }
            if (['number'].includes(column.property)) {
              // eslint-disable-next-line no-undef
              return XEUtils.sum(data, column.property)
            }
            return null
          })
        ]
        return footerData
      },
      twoDecimalPlaces (num) {
        let str = num.toString()
        var len1 = str.substr(0, 1)
        var len2 = str.substr(1, 1)
        // eslint-disable-next-line eqeqeq
        if (str.length > 1 && len1 == 0 && len2 != '.') {
          str = str.substr(1, 1)
        }
        // eslint-disable-next-line eqeqeq
        if (len1 == '.') {
          str = ''
        }
        // eslint-disable-next-line eqeqeq
        if (str.indexOf('.') != -1) {
          var str_ = str.substr(str.indexOf('.') + 1)
          // eslint-disable-next-line eqeqeq
          if (str_.indexOf('.') != -1) {
            str = str.substr(0, str.indexOf('.') + str_.indexOf('.') + 1)
          }
          if (str_.length > 2) {
            this.$message.warning(`金额小数点后只能输入两位，请正确输入！`)
            return (str = '')
          }
        }
        // eslint-disable-next-line no-useless-escape
        str = str.replace(/[^\d^\.]+/g, '') // 保留数字和小数点
        return str
      },
      isExict (row) {
        this.reimbursementService.checkNumber(row.number).then(({data}) => {
          if (data) {
            this.$message.error('该发票号已存在')
            row.number = ''
          }
        })
      },
      countAmount (row) {
        let amount
        let taxAmount
        let count = 0
        if (!this.commonJS.isEmpty(row.amount)) {
          amount = parseFloat(row.amount)
          count = count + amount
        }
        if (!this.commonJS.isEmpty(row.taxAmount)) {
          taxAmount = parseFloat(row.taxAmount)
          count = count + taxAmount
        }
        row.count = parseFloat(count).toFixed(2)
      },
      openProgramPageForm (rowIndex, row) {
        if (this.commonJS.isEmpty(row.typeName)) {
          this.$message.error('请选择报销项目')
          return
        }
        this.indexRow = rowIndex
        this.reimbursementTypeService.findById(row.typeId).then(({data}) => {
          console.log('typeInfo', data.sort)
          let i = data.sort.toString()
          i = i.substring(0, 1)
          // 非业务报销
          if (i !== '1') {
            this.$refs.programPageForm.init('2', false)
          } else {
            // 打开单选组件
            this.$refs.programPageForm.init(null, false)
          }
        })
      },
      getProgram (rows) {
        console.log('aaaaaaaaaaa', rows[0])
        this.inputForm.detailInfos[this.indexRow].projectId = rows[0].id
        this.inputForm.detailInfos[this.indexRow].projectName = rows[0].name
        this.inputForm.detailInfos[this.indexRow].reportNumber = rows[0].reportNo
        this.indexRow = ''
        this.$forceUpdate()
      },
      // 报销类型下拉弹窗
      typePullForm (rowIndex) {
        this.indexRow = rowIndex
        this.$refs.reimbursementTypePullForm.init()
      },
      getProgramForType (rows) {
        this.inputForm.detailInfos[this.indexRow].typeId = rows[0].id
        this.inputForm.detailInfos[this.indexRow].typeName = rows[0].name
        this.indexRow = ''
        this.$forceUpdate()
      },
      // 报销人下拉弹窗
      userPullListForm (rowIndex) {
        this.indexRow = rowIndex
        this.$refs.userPullForm.init()
      },
      getProgramForUser (rows) {
        console.log('rows', rows)
        this.inputForm.detailInfos[this.indexRow].userId = rows[0].id
        this.inputForm.detailInfos[this.indexRow].userName = rows[0].name
        this.inputForm.detailInfos[this.indexRow].deptId = rows[0].parentId
        this.inputForm.detailInfos[this.indexRow].deptName = rows[0].officeName
        this.indexRow = ''
        this.$forceUpdate()
      }
    }
  }
</script>
