<template>
  <div>
    <a-spin :spinning="spinning" tip="Loading...">
      <div>
        <div class="epenseCdfModal-con">
          <!-- 列表 -->
          <a-table
            class="sTable fixPagination"
            ref="table"
            :scroll="{ y: 300 }"
            size="small"
            :rowKey="(record,index) => 'cdfTable-'+index"
            :columns="columns"
            :data-source="dataList"
            :pagination="false"
            bordered>
            <div slot="customTitle1"><span style="color: red;">*</span>费用承担方类型</div>
            <div slot="customTitle2"><span style="color: red;">*</span>费用承担方</div>
            <div slot="customTitle3"><span style="color: red;">*</span>费用承担金额</div>
            <!-- 费用承担方类型 -->
            <template slot="fycdftype" slot-scope="text,record,index">
              <v-select
                :id="'cdfTable-splitObjType-'+index"
                code="EXPENSE_ACCOUNT_DETAIL_SPLIT_OBJ_TYPE"
                allowClear
                style="width: 100%;"
                :isEnable="true"
                v-model="record.splitObjType"
                @change="splitObjTypeChange(index)"
                placeholder="请选择承担方类型"
              ></v-select>
            </template>
            <!-- 费用承担方 -->
            <template slot="fycdf" slot-scope="text,record,index">
              <!-- 部门 -->
              <department :id="'cdfTable-department-'+index" v-show="record.splitObjType=='DEPARTMENT'" style="width: 100%;" placeholder="请选择承担方" v-model="record.splitObjSn"></department>
              <!-- 经销商 -->
              <custList
                v-show="record.splitObjType=='CUSTOMER'"
                cooperateFlag="1"
                @change="custChange"
                :id="'cust-'+index"
                :ref="'custList-'+record.no"
                placeholder="请选择(输入名称搜索)"></custList>
              <!-- 供应商 -->
              <supplier
                v-show="record.splitObjType=='SUPPLIER'"
                style="width: 100%;"
                enableFlag="1"
                :id="'cdfTable-supplier-'+index"
                v-model="record.splitObjSn"
                placeholder="请选择(输入名称搜索)"></supplier>
              <!-- 其它往来 -->
              <otherTransactions
                style="width: 100%;"
                :id="'cdfTable-otherTransactions-'+index"
                v-show="record.splitObjType=='OTHER_ORG'"
                v-model="record.splitObjSn"
                placeholder="请选择(输入名称搜索)"></otherTransactions>
              <span v-if="!record.splitObjType">--</span>
            </template>
            <!-- 费用承担金额 -->
            <template slot="amount" slot-scope="text,record,index">
              <a-input-number
                :id="'cdfTable-splitAmount-'+index"
                v-show="record.splitObjType"
                style="width: 100%;"
                v-model="record.splitAmount"
                @change="splitAmountChange"
                :precision="2"
                :min="0"
                :max="99999999"
                placeholder="请输入"
              />
              <span v-if="!record.splitObjType">--</span>
            </template>
            <!-- 承担人员 -->
            <template slot="cdry" slot-scope="text,record,index">
              <div
                style="display: flex;align-items: center;width: 100%;padding: 5px 0;border-bottom: 1px solid #eee;"
                v-for="(item,idx) in record.childDetailSplitList"
                :id="item.id"
                :key="item.id">
                <employee style="width: 50%;" placeholder="请选择承担人员" :notInSn="record.childDetailSplitList.filter(a=>a.splitObjSn!=item.splitObjSn).map(b=>b.splitObjSn)" v-model="item.splitObjSn"></employee>
                -
                <a-input-number
                  :id="'cdfTable-childsplitAmount-'+index"
                  style="width: 30%;"
                  v-model="item.splitAmount"
                  :precision="2"
                  :min="0"
                  :max="99999999"
                  placeholder="请输入费用"
                />
                <div style="padding-left: 15px;" v-if="record.childDetailSplitList&&record.childDetailSplitList.length>1">
                  <a-button
                    @click="handleDelCdry(record,idx)"
                    :id="'cdfTable-childsplitAmoun-del-'+index"
                    title="删除"
                    size="small"
                    type="danger"
                    shape="circle"
                    icon="minus" />
                </div>
                <div v-if="record.childDetailSplitList&&idx == record.childDetailSplitList.length - 1">
                  <a-button
                    @click="handleAddCdry(record,idx)"
                    :id="'cdfTable-childsplitAmoun-add-'+index"
                    title="添加承担人员"
                    size="small"
                    type="primary"
                    class="button-info"
                    shape="circle"
                    icon="plus" />
                </div>
              </div>
              <span v-if="record.childDetailSplitList&&record.childDetailSplitList.length==0">--</span>
            </template>
            <template slot="action" slot-scope="text,record,index">
              <a-button
                :id="'cdfTable-del-'+index"
                size="small"
                type="link"
                class="button-error"
                @click="handleDelRow(record,index)"
              >删除</a-button>
            </template>
            <template slot="footer" slot-scope="currentPageData">
              <a-button
                id="cdfTable-add-0"
                type="link"
                class="button-info"
                block
                @click="handleAddRow()"
              >+ 新增费用承担方</a-button>
            </template>
          </a-table>
        </div>
      </div>
    </a-spin>
  </div>
</template>

<script>
import { VSelect } from '@/components'
import department from './department.js'
import employee from './employee.js'
import custList from '@/views/common/custList.vue'
import supplier from '@/views/common/supplier.js'
import otherTransactions from '@/views/common/otherTransactions.js'
export default {
  components: { VSelect, department, employee, custList, supplier, otherTransactions },
  name: 'EpenseCdfModal',
  props: {
    list: { //  弹框显示状态
      type: Array,
      default: () => { return [] }
    }
  },
  watch: {
    // 费用明细列表
    list (newValue, oldValue) {
      this.dataList = JSON.parse(JSON.stringify(newValue))
      this.dataList.map(item => {
        item.no = item.id
        // 部门
        if (item.splitObjType == 'DEPARTMENT' && (!item.childDetailSplitList || item.childDetailSplitList.length == 0)) {
          this.$set(item, 'childDetailSplitList', [{
            splitObjType: 'EMPLOYEE',
            splitObjSn: undefined,
            splitAmount: 0
          }])
        }
        // 客户
        if (item.splitObjType == 'CUSTOMER') {
          this.$nextTick(() => {
            this.$refs['custList-' + item.no].setDufaultVal(item.splitObjName)
          })
        }
      })
      // 默认添加一条
      if (this.dataList.length == 0) {
        this.handleAddRow()
      }
    }
  },
  data () {
    return {
      spinning: false,
      dataList: [],
      columns: [
        { slots: { title: 'customTitle1' }, scopedSlots: { customRender: 'fycdftype' }, align: 'center', width: '15%' },
        { slots: { title: 'customTitle2' }, scopedSlots: { customRender: 'fycdf' }, align: 'center', width: '20%' },
        { slots: { title: 'customTitle3' }, scopedSlots: { customRender: 'amount' }, align: 'center', width: '15%' },
        { title: '承担人员-人员平摊费用', scopedSlots: { customRender: 'cdry' }, align: 'center', width: '40%' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ]
    }
  },
  mounted () {
    this.handleAddRow()
  },
  methods: {
    // 费用承担方类型
    splitObjTypeChange (index) {
      const row = this.dataList[index]
      console.log(index, row.splitObjType)
      row.splitObjSn = undefined
      // 只有部门有承担人员
      this.$set(row, 'childDetailSplitList', row.splitObjType == 'DEPARTMENT' ? [{
        splitObjType: 'EMPLOYEE',
        splitObjSn: undefined,
        splitAmount: Number(row.splitAmount).toFixed(2)
      }] : [])
      // 客户
      if (row.splitObjType == 'CUSTOMER') {
        this.$set(row, 'splitObjSn', undefined)
        this.$set(row, 'splitObjName', undefined)
        this.$refs['custList-' + row.no].dealerName = []
      }
      // 供应商
      if (row.splitObjType == 'SUPPLIER') {
        this.$set(row, 'splitObjSn', undefined)
      }
      // 费用合计
      this.$emit('fyTotal', this.fyTotal())
    },
    // 选择经销商
    custChange (v, obj, id) {
      const row = this.dataList[id.split('-')[1]]
      this.$set(row, 'splitObjSn', v.key)
      this.$set(row, 'splitObjName', obj.dealerName)
      this.$emit('fyTotal', this.fyTotal())
    },
    // 选择承担费用
    splitAmountChange () {
      this.$emit('fyTotal', this.fyTotal())
    },
    // 清空数据
    clearList () {
      this.dataList = []
    },
    // 获取数据
    getList () {
      let hasError = 0
      const list = this.dataList.filter(item => item.splitObjType && item.splitObjSn && item.splitAmount)
      const ret = JSON.parse(JSON.stringify(list))
      if (ret.length != this.dataList.length) {
        hasError = 1
      } else {
        ret.map(item => {
          // 如果时部门
          if (item.splitObjType == 'DEPARTMENT') {
            const al = item.childDetailSplitList.filter(a => !a.splitObjSn && a.splitAmount > 0)
            if (al.length) {
              hasError = 3
            } else {
              const dl = item.childDetailSplitList.filter(a => a.splitObjSn) || []
              // 有承担人员
              if (dl && dl.length) {
                let t = 0
                dl.map(b => t = Number(t) + Number(b.splitAmount))
                // console.log(Number(t), Number(item.splitAmount))
                hasError = (Number(t) != Number(item.splitAmount)) ? 2 : 0
              }
              item.childDetailSplitList = dl
            }
          }
        })
      }
      if (ret.length == 0) {
        hasError = 1
      }
      return [hasError, ret]
    },
    // 添加人员
    handleAddCdry (row, idx) {
      const cur = row.childDetailSplitList[idx]
      if (!cur.splitObjSn) {
        this.$message.info('请选择承担人员')
        return
      }
      if (cur.splitAmount <= 0) {
        this.$message.info('请输入平摊费用')
        return
      }
      // 校验承担费用合计是否超过费用承担金额
      let totalFy = 0
      row.childDetailSplitList.map(item => {
        totalFy = totalFy + Number(item.splitAmount)
      })
      // console.log(totalFy, row.splitAmount)
      if (totalFy >= Number(row.splitAmount).toFixed(2)) {
        this.$warning({
          title: '提示',
          content: '人员平摊费用合计必需等于费用承担金额'
        })
        return
      }
      // 已使用费用
      let ysyAmount = 0
      row.childDetailSplitList.map(item => {
        ysyAmount = ysyAmount + Number(item.splitAmount)
      })
      // 添加
      row.childDetailSplitList.push({
        splitObjType: 'EMPLOYEE',
        splitObjSn: undefined,
        splitAmount: Number(row.splitAmount - ysyAmount).toFixed(2)
      })
    },
    // 删除人员
    handleDelCdry (row, index) {
      row.childDetailSplitList.splice(index, 1)
    },
    // 添加承担费用
    handleAddRow () {
      this.dataList.push({
        no: new Date().getTime(),
        splitObjType: '',
        splitObjSn: undefined,
        splitAmount: 0,
        childDetailSplitList: []
      })
    },
    // 删除承担费用
    handleDelRow (a, index) {
      this.dataList.splice(index, 1)
      this.$emit('fyTotal', this.fyTotal())
      this.dataList.map(item => {
        if (item.splitObjType == 'CUSTOMER') {
          this.$nextTick(() => {
            this.$refs['custList-' + item.no].setDufaultVal(item.splitObjName)
          })
        }
      })
    },
    // 费用合计计算
    fyTotal: function () {
      let total = 0
      this.dataList.map(item => { total = total + item.splitAmount })
      return total.toFixed(2)
    }
  }
}
</script>

<style lang="less">
  .epenseCdfModal-modal{
    .ant-modal-body {
      padding: 30px 40px 24px;
    }
    .epenseCdfModal-con{
      text-align: center;
      h3{
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 25px;
      }
    }
    .btn-cont {
      text-align: center;
      margin: 35px 0 10px;
    }
  }
</style>
