<template>
  <a-modal
    centered
    class="epenseDetailModal-modal"
    :footer="null"
    :maskClosable="false"
    :title="title"
    v-model="isShow"
    @cancel="isShow=false"
    width="60%">
    <a-spin :spinning="spinning" tip="Loading...">
      <div>
        <div class="epenseDetailModal-con">
          <a-form-model
            id="epenseDetailModal-form"
            ref="ruleForm"
            :model="form"
            :rules="rules"
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol">
            <a-row>
              <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                <a-form-model-item label="记账类型" prop="accountType">
                  <v-select
                    code="EXPENSE_ACCOUNT_TYPE"
                    id="epenseDetailModal-accountType"
                    v-model="form.accountType"
                    allowClear
                    placeholder="请选择记账类型"
                  ></v-select>
                </a-form-model-item>
              </a-col>
              <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                <a-form-model-item label="记账名称" prop="accountNameSn">
                  <!-- 部门 -->
                  <department id="epenseDetailModal-accountName" v-show="form.accountType=='INNER_ACCOUNT'" @change="accountNameSnChange" v-model="form.accountNameSn" placeholder="请选择记账名称(输入名称搜索)"></department>
                  <!-- 经销商 -->
                  <custList
                    id="epenseDetailModal-accountName1"
                    v-show="form.accountType=='CUSTOMER'"
                    cooperateFlag="1"
                    dataAuthFlag="0"
                    ref="custList"
                    @change="accountNameSnChange"
                    placeholder="请选择记账名称(输入名称搜索)"></custList>
                  <!-- 供应商 -->
                  <supplier
                    id="epenseDetailModal-accountName2"
                    v-show="form.accountType=='OUT_ACCOUNT'"
                    enableFlag="1"
                    @change="accountNameSnChange"
                    v-model="form.accountNameSn"
                    placeholder="请选择记账名称(输入名称搜索)"></supplier>
                  <!-- 其它往来 -->
                  <otherTransactions id="epenseDetailModal-accountName3" v-show="form.accountType=='OTHER_ACCOUNT'" @change="accountNameSnChange" v-model="form.accountNameSn" placeholder="请选择记账名称(输入名称搜索)"></otherTransactions>
                  <span v-if="!form.accountType">
                    <a-select style="width: 100%" placeholder="请选择记账名称" id="epenseDetailModal-accountName4">
                      <a-select-option value="" :disabled="true" id="epenseDetailModal-accountName-kong">
                        请先选择记账类型
                      </a-select-option>
                    </a-select>
                  </span>
                </a-form-model-item>
              </a-col>
              <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                <a-form-model-item label="所属区域">
                  <subarea
                    id="epenseDetailModal-subarea"
                    ref="subareaBox"
                    defValKey="name"
                    :onlySubarea="true"
                    :changeOnSelect="false"
                    @change="subareaChange"
                    v-model="subareaList"
                    placeholder="请选择所属区域"
                  ></subarea>
                </a-form-model-item>
              </a-col>
              <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                <a-form-model-item label="所属省份" prop="provinceSn">
                  <Area id="epenseDetailModal-provinceSn" @change="provinceChange" placeholder="请选择所属省份" v-model="form.provinceSn"></Area>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                <a-form-model-item label="所属城市" prop="citySn">
                  <Area
                    id="epenseDetailModal-citySn"
                    ref="city"
                    @change="cityChange"
                    placeholder="请选择所属城市"
                    leve="city"
                    :parentId="form.provinceSn"
                    v-model="form.citySn"></Area>
                </a-form-model-item>
              </a-col>
              <a-col
                :xs="24"
                :sm="24"
                :md="12"
                :lg="12"
                :xl="12"
                v-if="!isBatch">
                <a-form-model-item label="记账费用">
                  <a-input
                    style="width: 100%;color: red;font-weight: bold;"
                    id="epenseDetailModal-expense"
                    :disabled="true"
                    :value="Math.abs(form.expense) * -1"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <a-form-model-item label="备注" prop="remarks" :label-col="{span:2}" :wrapper-col="{span:20}">
                  <a-textarea id="epenseDetailModal-remarks" placeholder="请输入备注(最多500个字符)" v-model="form.remarks" :rows="4" :maxLength="500"/>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
          <!-- 费用承担方 -->
          <epenseCdfModal v-if="!isBatch" ref="epenseCdf" :list="form.detailSplitList" @fyTotal="getFyTotal"></epenseCdfModal>
        </div>
        <div class="btn-cont">
          <a-button id="epenseDetailModal-back" @click="isShow = false" style="margin-right: 15px;">取消</a-button>
          <a-button type="primary" id="epenseDetailModal-save" @click="handleSave">确定</a-button>
        </div>
      </div>
    </a-spin>
  </a-modal>
</template>

<script>
import { VSelect } from '@/components'
import epenseCdfModal from './epenseCdfModal.vue'
import subarea from '@/views/common/subarea.js'
import Area from '@/views/common/area.js'
import custList from '@/views/common/custList.vue'
import supplier from '@/views/common/supplier.js'
import otherTransactions from '@/views/common/otherTransactions.js'
import department from './department.js'
import { expenseAcctDetailSave, expenseAcctDetailFindBySn } from '@/api/expenseManagement.js'
export default {
  name: 'EpenseDetailModal',
  components: { VSelect, subarea, Area, epenseCdfModal, custList, supplier, department, otherTransactions },
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    },
    expenseAccountSn: { // 报销单sn
      type: String,
      default: ''
    },
    expenseAccountNo: { // 报销单号
      type: String,
      default: ''
    },
    expenseAccountDetailSn: { // 明细sn
      type: String,
      default: ''
    },
    isBatch: { // 是否批量修改
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      spinning: false,
      isShow: this.openModal, //  是否打开弹框
      title: '',
      formItemLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 16 }
      },
      subareaList: [],
      form: {
        id: undefined,
        accountType: undefined, // 记帐类型
        accountNameSn: undefined, //  记账名称
        subareaArea: {
          subareaName: undefined, //  所属区域
          subareaAreaName: undefined // 分区
        },
        provinceSn: undefined, // 省份
        provinceName: '',
        citySn: undefined, // 市
        cityName: '',
        remarks: '', // 备注
        expense: 0, // 记账费用
        expenseAccountSn: '', // 报销单SN
        expenseAccountNo: '', // 报销单号
        expenseAccountDetailSn: '', // 报销明细sn
        detailSplitList: [] // 费用承担方明细
      },
      rules: {
        accountType: [
          { required: true, message: '请选择记帐类型', trigger: 'change' }
        ],
        accountNameSn: [
          { required: true, message: '请选择记账名称', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    // 费用合计
    getFyTotal (expense) {
      this.form.expense = expense
    },
    // 记账名称变化时
    accountNameSnChange (v, row) {
      console.log(v, row)
      if (this.form.accountType == 'CUSTOMER') {
        if (row) {
          this.form.accountNameSn = v.key
          this.form.provinceSn = row.provinceSn
          this.form.citySn = row.citySn
          this.form.provinceName = row.provinceName
          this.form.cityName = row.cityName
          this.form.subareaArea.subareaName = row.subareaArea ? row.subareaArea.subareaName : ''
          this.form.subareaArea.subareaAreaName = row.subareaArea ? row.subareaArea.subareaAreaName : ''
          this.subareaList = row.subareaArea ? [row.subareaArea.subareaName, row.subareaArea.subareaAreaName] : []
        } else {
          this.form.accountNameSn = ''
          this.form.provinceSn = ''
          this.form.citySn = ''
          this.form.provinceName = ''
          this.form.cityName = ''
          this.form.subareaArea.subareaName = ''
          this.form.subareaArea.subareaAreaName = ''
          this.$refs.subareaBox.clearData()
          this.subareaList = []
        }
      }
      this.$nextTick(() => {
        this.$refs.ruleForm.validateField('accountNameSn')
      })
    },
    // 分区
    subareaChange (val, row) {
      this.form.subareaArea.subareaName = val[0] ? val[0] : ''
      this.form.subareaArea.subareaAreaName = val[1] ? val[1] : ''
    },
    // 省
    provinceChange (v, row) {
      this.form.provinceName = row ? row.name : ''
      this.form.provinceSn = v || ''
      this.form.citySn = undefined
      this.form.cityName = ''
      this.$refs.city.clearData()
    },
    // 市
    cityChange (v, row) {
      this.form.cityName = row ? row.name : ''
      this.form.citySn = v || ''
    },
    // 详情
    getExpenseAccountDetail () {
      this.spinning = true
      expenseAcctDetailFindBySn({ detailSn: this.expenseAccountDetailSn }).then(res => {
        this.$nextTick(() => {
          this.form = Object.assign(this.form, res.data || {})
          this.form.provinceSn = this.form.provinceSn ? this.form.provinceSn : undefined
          this.form.citySn = this.form.citySn ? this.form.citySn : undefined
          setTimeout(() => {
            this.form.accountNameSn = res.data.accountNameSn
            if (res.data.accountType == 'CUSTOMER') {
              this.$refs.custList.setDufaultVal(res.data.accountName)
            }
            this.form.subareaArea.subareaName = res.data.subareaNames || ''
            this.form.subareaArea.subareaAreaName = res.data.subareaAreaName || ''
            this.subareaList = res.data.subareaNames ? [res.data.subareaNames, res.data.subareaAreaName] : undefined
          }, 200)
          this.spinning = false
        })
      })
    },
    // 确定
    handleSave (e) {
      e.preventDefault()
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const form = JSON.parse(JSON.stringify(_this.form))
          form.provinceName = form.provinceName ? form.provinceName : ''
          form.provinceSn = form.provinceSn ? form.provinceSn : ''
          form.citySn = form.citySn ? form.citySn : ''
          form.cityName = form.cityName ? form.cityName : ''

          // 如果是批量修改记账名称
          if (this.isBatch) {
            _this.spinning = true
            _this.$emit('ok', form)
          } else {
            // 校验明细承担人列表
            const cdfList = this.$refs.epenseCdf.getList()
            if (cdfList[0] == 1) {
              this.$warning({
                title: '是否存在以下情况，请按照要求填写',
                content: <div><p>1、费用承担方至少有一个</p><p>2、带星号的列为必填项,不能为空</p></div>,
                centered: true
              })
              return
            }
            if (cdfList[0] == 3) {
              this.$warning({
                title: '提示',
                content: '请检查每行承担人员是否已经选择',
                centered: true
              })
              return
            }
            if (cdfList[0] == 2) {
              this.$warning({
                title: '提示',
                content: '请检查每行人员平摊费用合计是否等于承担金额',
                centered: true
              })
              return
            }
            // 获取承担人列表数据
            form.detailSplitList = cdfList[1]
            form.expense = Math.abs(form.expense) // 费用合计

            _this.spinning = true
            expenseAcctDetailSave(form).then(res => {
              if (res.status == 200) {
                _this.$message.success(res.message)
                setTimeout(() => {
                  _this.$emit('ok')
                  _this.spinning = false
                }, 200)
              } else {
                _this.spinning = false
              }
            })
          }
        } else {
          return false
        }
      })
    },
    // 重置表单
    resetForm () {
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields()
        this.$refs.city.clearData()
        this.$refs.subareaBox.clearData()
      })
      this.form = {
        id: undefined,
        accountType: undefined, // 记帐类型
        accountNameSn: undefined, //  记账名称
        subareaArea: {
          subareaName: undefined, //  所属区域
          subareaAreaName: undefined // 分区
        },
        provinceSn: undefined, // 省份
        provinceName: '',
        citySn: undefined, // 市
        cityName: '',
        remarks: '', // 备注
        expense: 0, // 记账费用
        expenseAccountSn: '', // 报销单SN
        expenseAccountNo: '', // 报销单号
        expenseAccountDetailSn: '', // 报销明细sn
        detailSplitList: []
      }
      this.form.provinceSn = undefined
      this.form.provinceName = ''
      this.form.citySn = undefined
      this.form.cityName = ''
      this.form.expenseAccountSn = this.expenseAccountSn
      this.form.expenseAccountNo = this.expenseAccountNo
      this.subareaList = []
    }
  },
  watch: {
    'form.accountType' (newValue, oldValue) {
      this.form.accountNameSn = undefined
      this.$refs.custList.dealerName = []
    },
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
        this.resetForm()
      } else {
        this.form.expenseAccountSn = this.expenseAccountSn
        this.form.expenseAccountNo = this.expenseAccountNo
        // 编辑
        if (this.expenseAccountDetailSn) {
          this.title = '编辑费用明细'
          this.form.expenseAccountDetailSn = this.expenseAccountDetailSn || ''
          this.getExpenseAccountDetail()
        } else {
          this.resetForm()
          this.title = this.isBatch ? '批量变更记账名称' : '新增费用明细'
        }
      }
    }
  }
}
</script>

<style lang="less">
  .epenseDetailModal-modal{
    .ant-modal-body {
      padding: 30px 40px 24px;
    }
    .btn-cont {
      text-align: center;
      margin: 35px 0 10px;
    }
  }
</style>
