<template>
  <div class="expenseReimbursementAddwrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="expenseReimbursementAddcont" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="purchaseOrderEdit-back-btn" href="javascript:;" @click="handleBack(0)"><a-icon type="left" /> 返回列表</a>
        </template>
      </a-page-header>
      <a-collapse :activeKey="['1']" class="expenseReimbursementAddcont" v-if="detailData">
        <a-collapse-panel key="1" header="基础信息">
          <div slot="extra" style="padding: 0 20px; color: #00aaff;" @click.stop="handleEditBase" >
            <a-icon type="edit" /> 编辑基础信息
          </div>
          <a-descriptions :column="{ xs: 2, sm: 3, md: 3}">
            <a-descriptions-item label="费用单号">{{ detailData&&detailData.expenseAccountNo || '--' }}</a-descriptions-item>
            <a-descriptions-item label="申请人">{{ detailData&&detailData.applyPersonName || '--' }}</a-descriptions-item>
            <a-descriptions-item label="申请部门">{{ detailData&&detailData.applyDepartmentName || '--' }}</a-descriptions-item>
            <a-descriptions-item label="费用类型">{{ detailData&&detailData.expenseTypeName || '--' }}<span v-if="detailData&&detailData.expenseType2">/{{ detailData&&detailData.expenseTypeName2 || '--' }}</span></a-descriptions-item>
            <a-descriptions-item label="费用发生月份">{{ detailData&&detailData.expenseDate?detailData.expenseDate.substring(0, 7) : '--' }}</a-descriptions-item>
            <a-descriptions-item label="合计金额">{{ (detailData.applyExpenseTotal || detailData.applyExpenseTotal == 0) ? detailData.applyExpenseTotal+' 元' : '--' }}</a-descriptions-item>
            <a-descriptions-item label="状态">{{ detailData&&detailData.stateDictValue || '--' }}</a-descriptions-item>
            <a-descriptions-item label="创建时间">{{ detailData&&detailData.createDate || '--' }}</a-descriptions-item>
            <a-descriptions-item label="审核时间">{{ detailData&&detailData.finishDate || '--' }}</a-descriptions-item>
            <a-descriptions-item label="主题" :span="3">{{ detailData&&detailData.title || '--' }}</a-descriptions-item>
            <a-descriptions-item label="详细说明" :span="3">{{ detailData&&detailData.content.join('，')||'' }}</a-descriptions-item>
            <a-descriptions-item label="附件" :span="3">
              <a target="_blank" style="color: #00aaff;text-decoration: underline;margin-right: 15px;" :href="item.filePath" v-for="item in detailData.expenseAccountFilesList" :key="item.id">
                {{ item.fileName }}
              </a>
            </a-descriptions-item>
          </a-descriptions>
        </a-collapse-panel>
      </a-collapse>
      <!-- 费用明细 -->
      <a-card :bordered="false" size="small" class="expenseReimbursementAddcont" v-if="$route.params.sn">
        <div slot="title">
          <div style="display: flex;justify-content: space-between;align-items: center;">
            <div>费用明细</div>
            <div>
              <a-button size="small" class="button-info" type="primary" @click="openGuideModal=true">导入费用明细</a-button>
              <a-button size="small" class="button-error" type="primary" @click="newExpenseDetail">新增费用明细</a-button>
            </div>
          </div>
        </div>
        <a-alert type="info" style="margin-bottom:10px">
          <div slot="message">
            共{{ total }}条费用明细，合计金额￥{{ detailData&&detailData.applyExpenseTotal||0 }}元
          </div>
        </a-alert>
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :defaultLoadData="false"
          :showPagination="false"
          bordered>
          <template slot="action" slot-scope="text,record">
            <a-button
              size="small"
              type="link"
              class="button-info"
              @click="setProduct(record)"
            >设置产品信息</a-button>
            <a-button
              size="small"
              type="link"
              class="button-info"
              @click="handleEdit(record)"
            >编辑</a-button>
            <a-button
              size="small"
              type="link"
              class="button-error"
              @click="handleDel(record)"
            >删除</a-button>
          </template>
          <!-- 记账名称 -->
          <template slot="jzname" slot-scope="text,record">
            <div>{{ text }}</div>
            <div v-if="record.accountNameFnumber">({{ record.accountNameFnumber }})</div>
          </template>
          <!-- 费用承担方 -->
          <template slot="fycdf" slot-scope="text,record">
            <div v-for="(item,index) in record.detailSplitList" :key="item.id+'-'+index">
              {{ item.splitObjName }}
              <span v-if="item.splitObjFnumber">({{ item.splitObjFnumber }})</span>
              <span v-if="item.childDetailSplit&&item.childDetailSplit.splitObjName">/</span>
              {{ item.childDetailSplit?item.childDetailSplit.splitObjName:'' }}: ￥{{ item.childDetailSplit?item.childDetailSplit.splitAmount:item.splitAmount }}
            </div>
          </template>
          <!-- 产品信息 -->
          <template slot="cpxx" slot-scope="text,record">
            <div style="display:flex;align-items: center;" v-if="record.detailProductsList">
              <a-icon style="color:red;font-size:16px;" v-if="record.ptaFlag" type="exclamation-circle" />
              <div style="padding-left: 6px;">
                <div v-for="item in record.detailProductsList" :key="item.id">
                  <div v-if="item.productCode">{{ item.productCode }}: <span :style="{color:record.ptaFlag?'red':''}">￥{{ item.expense }}</span></div>
                  <div v-else-if="item.productBrandName">{{ item.productBrandName }}<span v-if="item.productTypeShowName">/</span>{{ item.productTypeShowName }}: <span :style="{color:record.ptaFlag?'red':''}">￥{{ item.expense }}</span></div>
                  <div v-else>{{ item.productTypeShowName }}: <span :style="{color:record.ptaFlag?'red':''}">￥{{ item.expense }}</span></div>
                </div>
              </div>
            </div>
            <div v-else>--</div>
          </template>
        </s-table>
      </a-card>
    </a-spin>
    <div class="affix-cont">
      <a-button
        type="primary"
        class="button-primary"
        :disabled="spinning"
        id="expenseReimbursementAddsubmit-btn"
        size="large"
        @click="beforeSubmit"
        style="padding: 0 60px;">提交</a-button>
    </div>
    <!-- 费用明细 -->
    <epenseDetailModal
      :openModal="openEpenseDetailModal"
      :expenseAccountSn="$route.params.sn"
      :expenseAccountNo="detailData?detailData.expenseAccountNo:''"
      :expenseAccountDetailSn="expenseAccountDetailSn"
      @ok="epenseDetailOk"
      @close="openEpenseDetailModal=false"></epenseDetailModal>
    <!-- 产品信息设置 -->
    <productInfoModal
      ref="productInfo"
      :openModal="openProductInfoModal"
      :expenseAccountSn="$route.params.sn"
      :expenseAccountNo="detailData?detailData.expenseAccountNo:''"
      :expenseAccountDetailSn="expenseAccountDetailSn"
      @ok="productInfoOk"
      @close="openProductInfoModal=false"></productInfoModal>
    <!-- 基础信息编辑 -->
    <baseDataModal :show="openBaseModal" @close="openBaseModal=false" :itemSn="$route.params.sn" @refashData="refashData"></baseDataModal>
    <!-- 导入费用明细 -->
    <ImportGuideModal :openModal="openGuideModal" :params="{expenseAccountSn: $route.params.sn, expenseAccountNo:detailData?detailData.expenseAccountNo:''}" @close="openGuideModal=false" @ok="hanldeImprotOk" />
    <!-- 选择审核人员 -->
    <chooseDepartUserModal :openModal="openDepartUserModal" @close="openDepartUserModal=false" @submit="handleSubmit"></chooseDepartUserModal>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { VSelect, Upload, STable } from '@/components'
import epenseDetailModal from './epenseDetailModal.vue'
import productInfoModal from './productInfoModal.vue'
import baseDataModal from './baseDataModal.vue'
import ImportGuideModal from './importGuideModal.vue'
import chooseDepartUserModal from './chooseDepartUserModal.vue'
import { expenseAccountDetail, expenseAcctDetailDelete, expenseAcctDetailFindList, expenseAccountSubmit, expenseInsertImport } from '@/api/expenseManagement.js'
export default {
  name: 'ExpenseReimbursementEdit',
  mixins: [commonMixin],
  components: { VSelect, Upload, STable, epenseDetailModal, productInfoModal, baseDataModal, ImportGuideModal, chooseDepartUserModal },
  data () {
    return {
      spinning: false,
      detailData: null,
      openBaseModal: false,
      openGuideModal: false,
      openDepartUserModal: false,
      openEpenseDetailModal: false, // 费用明细弹框
      expenseAccountDetailSn: '',
      openProductInfoModal: false, // 产品信息弹框
      total: 0,
      hasPtaFlag: [],
      loadData: parameter => {
        const params = Object.assign(parameter, { expenseAccountSn: this.$route.params.sn })
        return expenseAcctDetailFindList(params).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            const no = 0
            this.hasPtaFlag = []
            for (var i = 0; i < data.length; i++) {
              data[i].no = no + i + 1
              // 产品信息合计
              if (data[i].detailProductsList) {
                data[i].productTotalAmount = 0
                data[i].detailProductsList.map(item => {
                  data[i].productTotalAmount += item.expense
                })
                data[i].ptaFlag = data[i].productTotalAmount !== Math.abs(data[i].expense)
                if (data[i].ptaFlag) {
                  this.hasPtaFlag.push('第 ' + (i + 1) + ' 行')
                }
              }
            }
            this.total = data.length
            this.disabled = false
            this.spinning = false
          }
          return data
        })
      },
      columns: [
        { title: '序号', dataIndex: 'no', width: '5%', align: 'center' },
        { title: '记账类型', dataIndex: 'accountTypeDictValue', align: 'center', width: '8%', customRender: function (text) { return text || '--' } },
        { title: '记账名称', dataIndex: 'accountName', scopedSlots: { customRender: 'jzname' }, align: 'center', width: '10%' },
        { title: '所属区域', dataIndex: 'subareaNames', align: 'center', width: '8%', customRender: function (text) { return text || '--' } },
        { title: '所属省份', dataIndex: 'provinceName', align: 'center', width: '8%', customRender: function (text) { return text || '--' } },
        { title: '所属城市', dataIndex: 'cityName', align: 'center', width: '8%', customRender: function (text) { return text || '--' } },
        { title: '记账费用', dataIndex: 'expense', align: 'center', width: '10%', customRender: function (text) { return (text == 0 || text) ? text : '--' } },
        { title: '费用承担方', scopedSlots: { customRender: 'fycdf' }, align: 'center', width: '20%' },
        { title: '产品信息', scopedSlots: { customRender: 'cpxx' }, align: 'center', width: '15%' },
        { title: '备注', dataIndex: 'remarks', align: 'center', width: '10%', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '100px', align: 'center' }
      ]
    }
  },
  methods: {
    // 编辑基础信息
    handleEditBase (event) {
      this.openBaseModal = true
    },
    refashData () {
      this.getDetail(1)
    },
    //  费用单基础详情
    getDetail (type) {
      this.spinning = true
      this.disabled = true
      expenseAccountDetail({ expenseAccountSn: this.$route.params.sn }).then(res => {
        if (res.status == 200) {
          this.detailData = res.data
          this.detailData.content = res.data.content.replace(/\n+/, '\n').split('\n')
          if (!type) {
            // 获取费用明细列表
            this.getExpenseDetailList()
          } else {
            this.spinning = false
            this.disabled = false
          }
        }
      })
    },
    getExpenseDetailList () {
      this.$refs.table.refresh()
    },
    // 确认导入明细
    hanldeImprotOk (obj) {
      console.log(obj)
      expenseInsertImport(obj).then(res => {
        if (res.status == 200) {
          this.getDetail(false)
        }
      })
    },
    // 新增明细
    newExpenseDetail () {
      this.expenseAccountDetailSn = ''
      this.openEpenseDetailModal = true
    },
    // 新增明细成功
    epenseDetailOk () {
      // 刷新列表
      this.openEpenseDetailModal = false
      this.getDetail(false)
    },
    // 设置产品
    setProduct (row) {
      this.openProductInfoModal = true
      this.expenseAccountDetailSn = row.expenseAccountDetailSn
      this.$refs.productInfo.setBaseData(row)
    },
    // 新增产品成功
    productInfoOk () {
      // 刷新列表
      this.openProductInfoModal = false
      this.getDetail(false)
    },
    // 编辑明细
    handleEdit (row) {
      this.openEpenseDetailModal = true
      this.expenseAccountDetailSn = row.expenseAccountDetailSn
    },
    // 删除明细
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要删除吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.spinning = true
          expenseAcctDetailDelete({ detailSn: row.expenseAccountDetailSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.getDetail(false)
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    beforeSubmit () {
      if (this.total) {
        // 判断是否存在产品信息合计不等于记账费用
        if (this.hasPtaFlag.length) {
          const h = this.$createElement
          this.$warning({
            title: '操作提示',
            content: h('div', {}, [
              h('p', '提交失败，以下费用明细的产品信息金额之和，不等于记账费用，请修改后再提交！'),
              h('p', '需要修改的行数：'),
              h('p', { style: { color: '#00aaff' } }, this.hasPtaFlag.join('，'))
            ]),
            centered: true,
            onOk () {}
          })
        } else {
          this.openDepartUserModal = true
        }
      } else {
        this.$message.info('请新增费用明细')
      }
    },
    // 提交信息
    handleSubmit (data) {
      this.spinning = true
      expenseAccountSubmit({ expenseAccountSn: this.$route.params.sn, ...data }).then(res => {
        if (res.status == '200') {
          this.$message.success(res.message)
          this.handleBack()
        }
        this.spinning = false
      })
    },
    // 返回
    handleBack (data) {
      this.$router.push({ name: 'expenseReimbursementList' })
    },
    pageInit () {
      if (this.$route.params.sn) { //  编辑页
        this.getDetail()
      }
    }
  },
  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">
  .expenseReimbursementAddwrap{
    position: relative;
    height: 100%;
    padding-bottom: 51px;
    box-sizing: border-box;
    >.ant-spin-nested-loading{
      overflow-y: scroll;
      height: 100%;
    }
    .expenseReimbursementAddcont{
      margin-bottom: 10px;
    }
    .upload{
      width: 100%!important;
    }
    .affix{
      .ant-affix{
        z-index: 101;
      }
    }
  }
</style>
