<template>
  <div>
    <a-card size="small" :bordered="false" class="searchBoxNormal">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="15">
            <a-col :md="4" :sm="24">
              <a-form-item label="费用发生月份">
                <a-month-picker
                  placeholder="请选择月份"
                  locale="zh-cn"
                  v-model="queryParam.expenseDate"
                  @change="onChange"
                  :disabled-date="disabledDate"
                  style="width: 100%;"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="费用单号" :label-col="{ span:7 }" :wrapper-col="{ span:17}">
                <a-input id="salesManagementList-expenseAccountNo" v-model.trim="queryParam.expenseAccountNo" allowClear placeholder="请输入费用单号"/>
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <a-form-item label="申请人" :label-col="{ span:7 }" :wrapper-col="{ span:17}">
                <employee style="width: 100%;" id="salesManagementList-Employee" v-model="queryParam.applyPersonSn"></employee>
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <a-form-item label="费用类型">
                <expenseType
                  id="salesManagementList-expenseType"
                  :changeOnSelect="true"
                  v-model="expenseTypes"
                  @change="expenseChange"
                  placeholder="请选择费用类型"
                ></expenseType>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="主题">
                  <a-input id="salesManagementList-title" v-model.trim="queryParam.title" allowClear placeholder="请输入主题"/>
                </a-form-item>
              </a-col>
              <a-col :md="4" :sm="24">
                <a-form-item label="打印状态">
                  <v-select
                    v-model="queryParam.printStatus"
                    ref="printStatus"
                    id="pushOrder-printStatus"
                    code="EXPENSE_ACCOUNT_PRINT_STATUS"
                    placeholder="请选择打印状态"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="销售单号">
                  <a-input id="salesManagementList-salesBillNo" v-model.trim="queryParam.salesBillNo" allowClear placeholder="请输入销售单号"/>
                </a-form-item>
              </a-col>
              <a-col :md="4" :sm="24">
                <a-form-item label="状态">
                  <v-select
                    v-model="queryParam.state"
                    ref="state"
                    id="salesManagementList-state"
                    code="EXPENSE_STATE"
                    placeholder="请选择状态"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
            <!--  <a-col :md="4" :sm="24" v-show="isShowCustomerSearch">
                <a-form-item label="客服">
                  <customerService ref="customerName" v-model="queryParam.bizUserSn"></customerService>
                </a-form-item>
              </a-col> -->
            </template>
            <a-col :md="6" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" :disabled="disabled" @click="searchForm" id="salesManagementList-search">查询</a-button>
                <a-button style="margin-left: 8px" :disabled="disabled" @click="resetSearchForm()" id="salesManagementList-reset">重置</a-button>
                <a @click="advanced=!advanced" style="margin-left: 8px" id="salesManagementList-advanced">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card size="small" :bordered="false" class="salesManagementList-wrap">
      <a-spin :spinning="spinning" tip="Loading...">
        <!-- 操作按钮 -->
        <div class="table-operator">
          <a-button id="salesManagementList-add" type="primary" v-if="$hasPermissions('B_eRNew')" @click="handleEdit()">新增</a-button>
          <a-button
            id="salesManagementList-batchPrint"
            type="primary"
            v-if="$hasPermissions('B_eRPrint')"
            :loading="spinning"
            @click="handlePlPrint()"
            ghost>批量打印</a-button>
          <a-checkbox id="salesManagementList-print-remarks" v-model="printRemark" v-if="$hasPermissions('B_eRPrint')">打印备注</a-checkbox>
          <span style="margin-left: 8px" v-if="$hasPermissions('B_eRPrint')">
            <template v-if="rowSelectionInfo && rowSelectionInfo.selectedRowKeys.length>0">{{ `已选 ${rowSelectionInfo.selectedRowKeys.length} 项` }}</template>
          </span>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          :row-selection="$hasPermissions('B_eRPrint')?{ columnWidth: '4%', getCheckboxProps: record => ({ props: { disabled: false } })}:null"
          @rowSelection="rowSelectionFun"
          :style="{ height: tableHeight+70+'px' }"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :pageSize="30"
          :data="loadData"
          :scroll="{ y: tableHeight }"
          :defaultLoadData="false"
          bordered>
          <!-- 单号 -->
          <template slot="expenseAccountNo" slot-scope="text, record">
            <span :id="'salesManagementList-detail-'+record.id" v-if="$hasPermissions('B_eRdetail')" class="link-bule" @click="handleDetail(record)">{{ record.expenseAccountNo }}</span>
            <div v-else>{{ record.expenseAccountNo||'--' }}</div>
          </template>
          <!-- 总数量 -->
          <template slot="totalQty" slot-scope="text, record">
            {{ record.totalQty }}
          </template>
          <!-- 费用类型 -->
          <template slot="expenseType" slot-scope="text, record">
            <div>{{ record.expenseTypeName || '--' }}<span v-if="record.expenseType2">/{{ record.expenseTypeName2 || '--' }}</span><span v-if="record.expenseType3">/{{ record.expenseTypeName3 || '--' }}</span></div>
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <div>
              <a-button
                :id="'salesManagementList-edit-'+record.id"
                v-if="record.state=='WAIT_SUBMIT'&&$hasPermissions('B_ERtEdit')"
                size="small"
                type="link"
                class="button-info"
                @click="handleEdit(record)"
              >
                编辑
              </a-button>
              <a-button
                :id="'salesManagementList-audit-'+record.id"
                v-if="record.state!='WAIT_SUBMIT'&&$hasPermissions('B_ERAudit')"
                size="small"
                type="link"
                class="button-info"
                @click="handleSH(record)"
              >
                审核进度
              </a-button>
              <a-button
                :id="'salesManagementList-editAge-'+record.id"
                v-if="record.state=='AUDIT_REJECT'"
                size="small"
                type="link"
                class="button-info"
                @click="againEdit(record)"
              >
                再次编辑
              </a-button>
              <a-button
                :id="'salesManagementList-del-'+record.id"
                v-if="(record.state=='WAIT_SUBMIT'||record.state=='AUDIT_REJECT')&&$hasPermissions('B_ERDel')"
                size="small"
                type="link"
                class="button-error"
                @click="handleDel(record)"
              >
                删除
              </a-button>
            </div>
          </template>
        </s-table>
      </a-spin>
      <!-- 审核进度 -->
      <verifyModal v-drag :openModal="openModal" :itemSn="itemSn" :itemId="itemId" @close="openModal=false"></verifyModal>
      <!-- 新增 -->
      <baseDataModal :show="openBaseModal" @close="openBaseModal=false"></baseDataModal>
      <!-- 打印预览 -->
      <commonModal
        modalTit="费用报销单打印预览"
        width="700pt"
        okText="立即打印"
        :openModal="showTipModal"
        @cancel="showTipModal=false"
        @ok="$refs.printModal.prints()">
        <previewModal v-if="showTipModal" ref="printModal" @printOk="printOk"></previewModal>
      </commonModal>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN'
import moment from 'moment'
import subarea from '@/views/common/subarea.js'
import employee from './employee.js'
import { STable, VSelect } from '@/components'
import verifyModal from './verifyModal.vue'
import previewModal from './previewModal.vue'
import commonModal from '@/views/common/commonModal.vue'
import expenseType from '@/views/common/expenseType.js'
import customerService from '@/views/common/customerService'
import { expenseAccountList, expenseAccountDelete, expenseAccountAgainEdit, expenseAcctDetailFindList, expenseAccountUpdateBatch, getProcessInstance } from '@/api/expenseManagement'
import baseDataModal from './baseDataModal.vue'
export default {
  name: 'ExpenseReimbursementList',
  mixins: [commonMixin],
  components: { STable, VSelect, subarea, verifyModal, baseDataModal, employee, expenseType, previewModal, commonModal, customerService },
  data () {
    const _this = this
    return {
      locale,
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      disabled: false, //  查询、重置按钮是否可操作
      openModal: false, // 审核进度弹框是否显示
      openBaseModal: false, // 基础信息新建
      showTipModal: false, // 打印预览组件
      itemSn: '', // 费用单sn
      itemId: '', // 费用单id
      tableHeight: 0, // 表格高度
      expenseTypes: [], // 费用类型
      // 查询参数
      queryParam: {
        expenseDate: moment().format('YYYY-MM'), // 月份
        expenseAccountNo: '', // 费用单号
        title: '', //  主题
        expenseType: undefined, // 费用类型
        expenseType2: undefined, // 费用类型2
        expenseType3: undefined, // 费用类型3
        printStatus: undefined, // 打印状态
        state: undefined, // 状态
        salesBillNo: '', // 销售单号
        bizUserSn: undefined // 客服
      },
      columns: [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '费用单号', width: '8%', align: 'center', scopedSlots: { customRender: 'expenseAccountNo' } },
        { title: '申请人', dataIndex: 'applyPersonName', width: '6%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '申请部门', dataIndex: 'applyDepartmentName', width: '8%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '费用类型', scopedSlots: { customRender: 'expenseType' }, width: '8%', align: 'left' },
        { title: '费用发生月份', dataIndex: 'expenseDate', width: '6%', align: 'center', customRender: function (text) { return moment(text).format('YYYY年MM月') || '--' } },
        { title: '主题', dataIndex: 'title', width: '10%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '合计金额', dataIndex: 'applyExpenseTotal', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '创建时间', dataIndex: 'createDate', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '审核时间', dataIndex: 'finishDate', width: '8%', align: 'center', customRender: function (text, record) { return record.state == 'AUDIT_REJECT' || record.state == 'AUDIT_PASS' ? text : '--' } },
        { title: '打印状态', dataIndex: 'printStatusDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '状态', dataIndex: 'stateDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        delete parameter.tableId
        delete parameter.index
        const params = Object.assign(parameter, this.queryParam)
        if (params.expenseDate) {
          params.expenseDate = params.expenseDate + '-01'
        }
        return expenseAccountList(params).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            const no = (data.pageNo - 1) * data.pageSize
            for (var i = 0; i < data.list.length; i++) {
              data.list[i].no = no + i + 1
              data.list[i].content = data.list[i].content ? data.list[i].content.replace(/\n+/, '\n').split('\n') : ''
            }
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      },
      rowSelectionInfo: null, // 批量选择的数据
      printRemark: false // 是否打印备注
    }
  },
  methods: {
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    // 打印结束，记录打印状态
    printOk (data) {
      if (data && data.status == 200) {
        const rows = this.rowSelectionInfo && this.rowSelectionInfo.selectedRows || []
        const ret = []
        rows.map(item => {
          ret.push({
            id: item.id,
            printStatus: 'PRINT'
          })
        })
        expenseAccountUpdateBatch(ret).then(res => {
          if (res.status == 200) {
            this.$refs.table.refresh()
            this.$refs.table.clearSelected()
          }
          this.spinning = false
          this.showTipModal = false
        })
      } else {
        this.spinning = false
      }
    },
    // 批量打印
    async handlePlPrint () {
      const _this = this
      const rows = _this.rowSelectionInfo && _this.rowSelectionInfo.selectedRows || []
      const slen = rows.length
      if (!_this.rowSelectionInfo || (_this.rowSelectionInfo && slen < 1)) {
        _this.$message.warning('请在列表勾选后再进行批量操作！')
        return false
      }
      // 开始打印
      this.spinning = true
      const pageData = []
      let newSpListData = []
      // 循环获取
      for (let i = 0; i < rows.length; i++) {
        // 费用明细
        const fyListData = await expenseAcctDetailFindList({ expenseAccountSn: rows[i].expenseAccountSn }).then(res => res.data)
        // 审核明细,待提交状态不获取
        if (rows[i].state != 'WAIT_SUBMIT') {
          // 获取审核进度信息
          newSpListData = await getProcessInstance({ 'businessType':'EXPENSES', 'businessSn': rows[i].expenseAccountSn }).then(res => res.data[0].opinionList || [])
        }
        // 组装数据
        pageData.push({
          printRemark: this.printRemark,
          expenseInfo: rows[i],
          fyListData: fyListData,
          spListData: newSpListData
        })
      }
      
      // 打开预览弹框
      this.showTipModal = true
      this.$nextTick(() => {
        this.$refs.printModal.setData(pageData)
        this.spinning = false
      })
    },
    // 费用发生月份
    onChange (date, dateString) {
      this.queryParam.expenseDate = dateString
    },
    // 费用发生月份禁用范围
    disabledDate (current) {
      return current && current > moment().endOf('day')
    },
    // 费用类型选择
    expenseChange (val, opts) {
      this.expenseTypes = val || []
      this.queryParam.expenseType = val && val[0] ? val[0] : ''
      this.queryParam.expenseType2 = val && val[1] ? val[1] : ''
      this.queryParam.expenseType3 = val && val[2] ? val[2] : ''
    },
    // 详情页面
    handleDetail (row) {
      this.$router.push({ name: 'expenseReimbursementListDetail', params: { sn: row.expenseAccountSn, itemId: row.id } })
    },
    // 新增、编辑
    handleEdit (row) {
      // 编辑
      if (row && row.expenseAccountSn) {
        this.$router.push({ name: 'expenseReimbursementEdit', params: { sn: row.expenseAccountSn } })
      } else {
        this.openBaseModal = true
      }
    },
    // 删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确定删除该单据吗，删除后不可恢复？',
        centered: true,
        closable: true,
        onOk () {
          _this.spinning = true
          expenseAccountDelete({ expenseAccountSn: row.expenseAccountSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
            }
            _this.spinning = false
          })
        }
      })
    },
    // 审核进度弹框
    handleSH (row) {
      // debugger
      this.openModal = true
      this.itemSn = row.expenseAccountSn
      this.itemId = row.id
    },
    // 再次编辑
    againEdit (row) {
      const _this = this
      this.$confirm({
        title: '操作提示',
        content: '系统将自动生成一个新的费用报销单，与原审核不通过的单据内容相同。您可以对新单据进行编辑、提交等操作，原单据保持不变，确认操作吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.spinning = true
          expenseAccountAgainEdit({ expenseAccountSn: row.expenseAccountSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.resetSearchForm()
            }
            _this.spinning = false
          })
        }
      })
    },
    // 查询列表
    searchForm () {
      this.$refs.table.refresh(true)
      this.$refs.table.clearSelected()
    },
    // 重置列表
    resetSearchForm () {
      this.queryParam = {
        expenseDate: '', // 月份
        expenseAccountNo: '', // 费用单号
        title: '', //  主题
        expenseType: undefined, // 费用类型
        expenseType2: undefined, // 费用类型2
        expenseType3: undefined, // 费用类型3
        state: undefined, // 状态
        printStatus: undefined,
        applyPersonSn: undefined,
        salesBillNo: '', // 销售单号
        bizUserSn: undefined
      }
      this.expenseTypes = []
      this.searchForm()
    },
    // 页面初始化
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 240
    }
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.resetSearchForm()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
      this.resetSearchForm()
    }
    // 仅刷新列表，不重置页面
    if (this.$store.state.app.updateList) {
      this.pageInit()
      this.$refs.table.refresh()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
<style lang="less">
  .salesManagementList-wrap{
    .sTable{
      .badge-con-t{
        .ant-badge-count{
          transform: scale(0.8);
          font-size: 13px;
        }
      }
    }
  }
</style>
