<template>
  <div class="expenseReimbursementAddwrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="expenseReimbursementAddcont" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="expenseEdit-back-btn" href="javascript:;" @click="handleBack(0)"><a-icon type="left" /> 返回列表</a>
          <span style="margin: 0 15px;color: #666;font-weight: bold;">单号：{{ detailData&&detailData.expenseAccountNo }}</span>
          <span style="margin: 0 10px;color: #666;">申请人：{{ detailData&&detailData.applyPersonName || '--' }}</span>
          <a-button size="small" type="link" class="button-default" id="expenseEdit-showdesc" @click="showDetail=!showDetail">
            <a-icon :type="showDetail ? 'eye-invisible' : 'eye'"/> {{ showDetail?'隐藏':'查看' }}信息
          </a-button>
        </template>
      </a-page-header>
      <a-card :bordered="false" size="small" class="expenseReimbursementAddcont" v-show="showDetail">
        <div slot="title">
          <span>基础信息</span>
          <div style="cursor:pointer;color: #00aaff;float:right;" id="expenseEdit-showEditModal" @click.stop="handleEditBase" >
            <a-icon type="edit" /> 编辑基础信息
          </div>
        </div>
        <a-descriptions :column="{ xs: 2, sm: 3, md: 4}" v-if="detailData">
          <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><span v-if="detailData&&detailData.expenseType3">/{{ detailData&&detailData.expenseTypeName3 || '--' }}</span></a-descriptions-item>
          <a-descriptions-item label="费用归属品牌">
            {{ (detailData&&detailData.productBrandName) || '--' }}
          </a-descriptions-item>
          <a-descriptions-item label="费用归属品类">
            <div>
              <span v-if="detailData&&detailData.productTypeName1">{{ detailData.productTypeName1 || '--' }}</span>
              <span v-else>--</span>
              <span v-if="detailData&&detailData.productTypeName2">/{{ detailData.productTypeName2 || '--' }}</span>
              <span v-if="detailData&&detailData.productTypeName3">/{{ detailData.productTypeName3 || '--' }}</span>
            </div>
          </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) ? toThousands(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="关联单号" v-if="detailData&&detailData.bizNo">{{ detailData&&detailData.bizNo || '--' }}</a-descriptions-item>
          <a-descriptions-item label="主题" :span="3">{{ detailData&&detailData.title || '--' }}</a-descriptions-item>
          <a-descriptions-item label="详细说明" :span="4">{{ detailData&&detailData.content.join('，')||'' }}</a-descriptions-item>
          <a-descriptions-item label="摘要" :span="4">
            {{ detailData.digestInfo||'' }}
          </a-descriptions-item>
          <a-descriptions-item label="附件" :span="4">
            <a
              target="_blank"
              style="color: #00aaff;text-decoration: underline;margin-right: 15px;"
              :href="item.filePath"
              v-for="item in detailData.expenseAccountFilesList"
              :id="item.id"
              :key="item.id">
              {{ item.fileName }}
            </a>
          </a-descriptions-item>
        </a-descriptions>
      </a-card>
      <!-- 费用明细 -->
      <a-card :bordered="false" size="small" class="expenseContent">
        <div slot="title">
          <div style="display: flex;justify-content: space-between;align-items: center;">
            <div>费用明细</div>
            <div>
              <a-button id="expenseEdit-plEdit" size="small" class="button-info" type="primary" @click="plEdit">变更记账名称</a-button>
              <a-button id="expenseEdit-import" size="small" class="button-info" type="primary" @click="openGuideModal=true">导入费用明细</a-button>
              <a-button id="expenseEdit-new" 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?toThousands(detailData.applyExpenseTotal) :'￥0.00' }}元
          </div>
        </a-alert>
        <!-- 列表 -->
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :row-selection="{ columnWidth: 40 }"
          @rowSelection="rowSelectionFun"
          :defaultLoadData="false"
          :showPagination="false"
          bordered>
          <template slot="action" slot-scope="text,record">
            <a-button
              size="small"
              type="link"
              class="button-info"
              @click="setProduct(record)"
              :id="'expenseEdit-set-'+record.id"
            >设置产品信息</a-button>
            <a-button
              size="small"
              type="link"
              class="button-info"
              @click="handleEdit(record)"
              :id="'expenseEdit-edit-'+record.id"
            >编辑</a-button>
            <a-button
              size="small"
              type="link"
              class="button-error"
              @click="handleDel(record)"
              :id="'expenseEdit-del-'+record.id"
            >删除</a-button>
          </template>
          <!-- 记账名称 -->
          <template slot="jzname" slot-scope="text,record">
            <div>{{ text }}</div>
            <div v-if="record.accountNameFnumber">({{ record.accountNameFnumber }})</div>
          </template>
          <!-- 原记账名称 -->
          <template slot="yjzname" slot-scope="text,record">
            <div>{{ text == record.accountName || !text ? '--' : text }}</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 v-if="record.detailProductsList">
              <div>
                <div v-for="item in record.detailProductsList" :key="item.id">
                  <div v-if="item.productCode">{{ item.productCode }}</div>
                  <div v-else-if="item.productBrandName">{{ item.productBrandName }}<span v-if="item.productTypeShowName">/</span>{{ item.productTypeShowName }}</div>
                  <div v-else>{{ item.productTypeShowName }}</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
      ref="epenseDetailForm"
      :openModal="openEpenseDetailModal"
      :expenseAccountSn="$route.params.sn"
      :expenseAccountNo="detailData?detailData.expenseAccountNo:''"
      :expenseAccountDetailSn="expenseAccountDetailSn"
      :isBatch="isBatch"
      @ok="epenseDetailOk"
      @close="epenseDetailClose"></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, updateBatchExpenseAcctDetail, expenseAcctDetailFindList, expenseAccountSubmit, expenseInsertImport } from '@/api/expenseManagement.js'
export default {
  name: 'ExpenseReimbursementEdit',
  mixins: [commonMixin],
  components: { VSelect, Upload, STable, epenseDetailModal, productInfoModal, baseDataModal, ImportGuideModal, chooseDepartUserModal },
  data () {
    const _this = this
    return {
      spinning: false,
      detailData: null, // 详情信息
      openBaseModal: false, // 基础信息编辑弹框
      openGuideModal: false, // 导入费用明细弹框
      openDepartUserModal: false, // 选择审核人员弹框
      openEpenseDetailModal: false, // 费用明细弹框
      expenseAccountDetailSn: '', // 费用明细sn
      openProductInfoModal: false, // 产品信息弹框
      showDetail: false, // 是否显示详细信息
      total: 0, // 总记录数
      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
            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
                })
              }
            }
            this.total = data.length
            this.disabled = false
            this.spinning = false
          }
          return data
        })
      },
      columns: [
        { title: '序号', dataIndex: 'no', width: '4%', 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: 'origAccountName', scopedSlots: { customRender: 'yjzname' }, align: 'center', width: '10%' },
        { title: '所属区域', dataIndex: 'subareaNames', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '所属分区', dataIndex: 'subareaAreaName', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '所属省份', dataIndex: 'provinceName', align: 'center', width: '5%', customRender: function (text) { return text || '--' } },
        { title: '所属城市', dataIndex: 'cityName', align: 'center', width: '5%', customRender: function (text) { return text || '--' } },
        { title: '记账费用', dataIndex: 'expense', align: 'center', width: '8%', customRender: function (text) { return (text == 0 || text) ? _this.toThousands(text) : '--' } },
        { title: '费用承担方', scopedSlots: { customRender: 'fycdf' }, align: 'center', width: '15%' },
        { title: '产品信息', scopedSlots: { customRender: 'cpxx' }, align: 'center', width: '10%' },
        { title: '销售单号', dataIndex: 'salesBillNo', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '备注', dataIndex: 'remarks', align: 'center', width: '10%', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '100px', align: 'center' }
      ],
      isBatch: false, // 是否变更记账名称
      rowSelectionInfo: null // 批量选择的数据
    }
  },
  methods: {
    // 编辑基础信息
    handleEditBase (event) {
      this.openBaseModal = true
    },
    // 刷新列表
    refashData () {
      this.getDetail(true)
    },
    //  获取费用单基础详情
    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) {
      expenseInsertImport(obj).then(res => {
        if (res.status == 200) {
          this.getDetail(false)
        }
      })
    },
    // 批量修改明细
    plEdit () {
      if (!this.rowSelectionInfo || (this.rowSelectionInfo && this.rowSelectionInfo.selectedRowKeys.length < 1)) {
        this.$message.warning('请在列表勾选后再进行操作！')
        return
      }
      this.expenseAccountDetailSn = ''
      this.openEpenseDetailModal = true
      this.isBatch = true
    },
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    // 新增明细
    newExpenseDetail () {
      this.expenseAccountDetailSn = ''
      this.openEpenseDetailModal = true
    },
    // 编辑明细
    handleEdit (row) {
      this.openEpenseDetailModal = true
      this.expenseAccountDetailSn = row.expenseAccountDetailSn
    },
    // 新增修改明细成功
    epenseDetailOk (data) {
      // 如果是批量修改
      if (this.isBatch) {
        const rows = this.rowSelectionInfo && this.rowSelectionInfo.selectedRows || []
        const params = []
        if (rows.length) {
          rows.forEach(item => {
            params.push({
              expenseAccountDetailSn: item.expenseAccountDetailSn,
              origAccountName: item.origAccountName,
              origAccountNameSn: item.origAccountNameSn,
              accountNameSn: data.accountNameSn,
              accountType: data.accountType,
              provinceName: data.provinceName,
              provinceSn: data.provinceSn,
              subareaArea: data.subareaArea,
              cityName: data.cityName,
              citySn: data.citySn,
              expenseAccountNo: data.expenseAccountNo,
              expenseAccountSn: data.expenseAccountSn,
              remarks: data.remarks
            })
          })
          // 组织数据
          updateBatchExpenseAcctDetail(params).then(res => {
            if (res.status == 200) {
              this.$message.success(res.message)
              // 修改成功
              this.$refs.table.clearTable()
              this.epenseDetailClose()
              this.getDetail(false)// 刷新列表
            }
            this.$refs.epenseDetailForm.spinning = false
          })
        } else {
          this.$message.warning('请在列表勾选后再进行操作！')
          this.$refs.epenseDetailForm.spinning = false
        }
      } else {
        // 单个修改成功
        this.epenseDetailClose()
        this.getDetail(false)// 刷新列表
      }
    },
    // 明细弹框关闭
    epenseDetailClose () {
      this.openEpenseDetailModal = false
      this.isBatch = false
    },
    // 删除明细
    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
            }
          })
        }
      })
    },
    // 设置产品
    setProduct (row) {
      this.openProductInfoModal = true
      this.expenseAccountDetailSn = row.expenseAccountDetailSn
      this.$refs.productInfo.setBaseData(row)
    },
    // 新增产品成功
    productInfoOk () {
      // 刷新列表
      this.openProductInfoModal = false
      this.getDetail(false)
    },
    // 提交前，选择审批人员
    beforeSubmit () {
      if (this.total) {
        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 () {
      this.$refs.table.clearTable()
      if (this.$route.params.sn) { //  编辑页
        this.getDetail(false)
      }
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    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: 6px;
    }
    .expenseContent{
      min-height: calc(100vh - 190px);
    }
    .upload{
      width: 100%!important;
    }
    .affix{
      .ant-affix{
        z-index: 101;
      }
    }
  }
</style>
