<template>
  <div class="expenseManagementEdit-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :back-icon="false" class="expenseManagementEdit-back">
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="expenseManagementEdit-back-btn" href="javascript:;" @click="handleBack">
            <a-icon type="left"></a-icon>
            返回列表
          </a>
        </template>
      </a-page-header>
      <a-card size="small" :bordered="false" class="expenseManagementEdit-table-page-wrapper">
        <a-form-model
          id="expenseManagementEdit-form"
          ref="ruleForm"
          :model="form"
          :rules="rules"
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol">
          <a-form-model-item label="费用类型" prop="costType">
            <a-cascader
              @change="changeCostType"
              v-model="form.costType"
              expand-trigger="hover"
              :options="costTypeList"
              :fieldNames="{ label: 'name', value: 'costTypeSn', children: 'children' }"
              id="productInfoList-costType"
              placeholder="请选择费用类型"
              allowClear
            />
          </a-form-model-item>
          <a-form-model-item label="费用金额" prop="settleAmount">
            <a-input-number
              id="expenseManagementEdit-name"
              v-model="form.settleAmount"
              :precision="2"
              :min="0"
              :max="999999"
              placeholder="请输入费用金额(0~999999)"
              allowClear
              style="width: 90%;"
            />
            元
          </a-form-model-item>
          <a-form-model-item label="结算方式" prop="settleStyleSn">
            <a-select placeholder="请选择结算方式" allowClear v-model="form.settleStyleSn" @change="settleStyleChange">
              <a-select-option v-for="item in settleStyleList" :key="item.settleStyleSn" :value="item.settleStyleSn">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="关联单号" prop="bizNo">
            <a-input id="expenseManagementEdit-bizNo" :maxLength="30" v-model.trim="form.bizNo" placeholder="请输入关联单号(最多30个字符)" allowClear />
          </a-form-model-item>
          <a-form-model-item label="备注" prop="remark">
            <a-textarea id="expenseManagementEdit-remarks" :maxLength="500" v-model="form.remark" placeholder="请输入备注(最多500个字符)" allowClear />
          </a-form-model-item>
          <a-form-model-item :wrapper-col="{ span: 12, offset: 6 }" style="text-align: center;">
            <a-button type="primary" @click="handleSubmit" id="expenseManagementEdit-btn-save" style="margin: 0 30px;">保存</a-button>
          </a-form-model-item>
        </a-form-model>
      </a-card>
    </a-spin>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import { settleExpenseSave, findExpenseDetail } from '@/api/settleExpense'
import { costTypeAllQuery } from '@/api/costType'
import { settleStyleQueryAll } from '@/api/settleStyle'
export default {
  name: 'ExpenseManagementEdit',
  components: { STable, VSelect },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      formItemLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 16 }
      },
      costTypeList: [], // 费用类型
      settleStyleList: [], // 结算方式
      form: {
        expensesTypeSn1: '', // 费用类型
        expensesTypeSn2: '', // 费用类型1
        expensesTypeSn3: '', // 费用类型2
        costType: [],
        settleAmount: '', //  费用金额
        settleStyleSn: undefined, //  结算方式
        settleStyleName: '', // 结算方式名称
        bizNo: '', //  关联单号
        remark: '' //  备注
      },
      rules: {
        costType: [{ required: true, message: '请选择费用类型', trigger: 'change' }],
        settleAmount: [{ required: true, message: '请输入费用金额', trigger: 'blur' }],
        settleStyleSn: [{ required: true, message: '请选择结算方式', trigger: 'change' }]
      }
    }
  },
  methods: {
    // 获取结算方式
    getSettleStyle () {
      settleStyleQueryAll().then(res => {
        if (res.status == 200) {
          this.settleStyleList = res.data
        }
      })
    },
    // 选择结算方式
    settleStyleChange (v) {
      this.form.settleStyleName = this.settleStyleList.find(item => item.settleStyleSn == v).name
    },
    //  递归函数
    recursionFun (data) {
      if (data) {
        data.map((item, index) => {
          if (item.children && item.children.length == 0) {
            delete item.children
          } else {
            this.recursionFun(item.children)
          }
        })
      }
    },
    // 获取费用类型数据
    getCostTypeList () {
      costTypeAllQuery({}).then(res => {
        //  递归去除空children
        this.recursionFun(res.data)
        this.costTypeList = res.data
      })
    },
    //  费用类型  change
    changeCostType (val, opt) {
      this.form.expensesTypeSn1 = val[0] ? val[0] : ''
      this.form.expensesTypeSn2 = val[1] ? val[1] : ''
      this.form.expensesTypeSn3 = val[2] ? val[2] : ''
      this.form.expensesTypeName1 = val[0] ? opt[0].name : ''
      this.form.expensesTypeName2 = val[1] ? opt[1].name : ''
      this.form.expensesTypeName3 = val[2] ? opt[2].name : ''
    },
    //  详情
    getDetail () {
      findExpenseDetail({ id: this.$route.params.id }).then(res => {
        if (res.status == 200) {
          this.form = Object.assign({}, this.form, res.data)
          this.form.costType = [this.form.expensesTypeSn1, this.form.expensesTypeSn2, this.form.expensesTypeSn3]
        } else {
          this.$refs.ruleForm.resetFields()
        }
      })
    },
    //  保存
    handleSubmit (e) {
      e.preventDefault()
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (this.form.settleAmount <= 0) {
            this.$message.warning('费用金额必须大于0！')
            return
          }
          const form = JSON.parse(JSON.stringify(_this.form))
          if (this.$route.params.id) {
            form.id = this.$route.params.id
          }
          delete form.costType
          _this.spinning = true
          settleExpenseSave(form).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              setTimeout(() => {
                _this.handleBack()
                _this.spinning = false
              }, 1000)
            } else {
              _this.spinning = false
            }
          })
        } else {
          return false
        }
      })
    },
    //  返回列表
    handleBack () {
      this.$router.push({ path: '/financialManagement/expenseManagement/list' })
    },
    pageInit () {
      const vm = this
      vm.$refs.ruleForm.resetFields()
      if (vm.$route.params.id) {
        //  编辑页
        vm.getDetail()
      }
      vm.getCostTypeList()
      vm.getSettleStyle()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.pageInit()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
.expenseManagementEdit-wrap {
  height: 100%;
  >.ant-spin-nested-loading{
    height: 100%;
    .ant-spin-container{
      height: 90%;
    }
  }
  .expenseManagementEdit-back {
    margin-bottom: 10px;
  }
  .expenseManagementEdit-table-page-wrapper{
    height: 100%;
  }
}
</style>
