<template>
  <a-card size="small" :bordered="false" class="expenseManagementList-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="$refs.table.refresh(true)">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-item label="费用单号">
                <a-input id="expenseManagementList-accountExpensesNo" v-model.trim="queryParam.accountExpensesNo" allowClear placeholder="请输入费用单号"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="创建时间">
                <rangeDate ref="rangeDate" @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="费用类型">
                <a-cascader
                  @change="changeCostType"
                  change-on-select
                  v-model="costType"
                  expand-trigger="hover"
                  :options="costTypeList"
                  :fieldNames="{ label: 'name', value: 'costTypeSn', children: 'children' }"
                  id="productInfoList-costType"
                  placeholder="请选择费用类型"
                  allowClear />
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="单据状态">
                  <v-select
                    v-model="queryParam.state"
                    ref="state"
                    id="expenseManagementList-state"
                    code="EXPENSE_AUDIT_TYPE"
                    placeholder="请选择单据状态"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="expenseManagementList-refresh">查询</a-button>
                <a-button style="margin-left: 8px" @click="resetSearchForm()" :disabled="disabled" id="expenseManagementList-reset">重置</a-button>
                <a @click="advanced=!advanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 操作按钮 -->
      <div class="table-operator">
        <a-button v-if="$hasPermissions('B_expenseNew')" id="expenseManagementList-add" type="primary" class="button-error" @click="handleEdit()">新增</a-button>
      </div>
      <!-- alert -->
      <a-alert type="info" showIcon style="margin-bottom:15px">
        <div slot="message">
          共 <strong>{{ totalData&&(totalData.count || totalData.count==0) ? totalData.count : '--' }}</strong> 条记录，
          金额共计 <strong>￥{{ totalData&&(totalData.totalAmount || totalData.totalAmount==0) ? '￥'+totalData.totalAmount : '--' }}</strong>
        </div>
      </a-alert>
      <!-- 列表 -->
      <s-table
        class="sTable"
        ref="table"
        size="default"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :scroll="{ x: 1120, y: tableHeight }"
        bordered>
        <!-- 费用类别 -->
        <template slot="expensesType" slot-scope="text, record">
          {{ record.expensesTypeName1 }} <span v-if="record.expensesTypeName2">>{{ record.expensesTypeName2 }}</span> <span v-if="record.expensesTypeName3">>{{ record.expensesTypeName3 }}</span>
        </template>
        <!-- 状态 -->
        <template slot="accountExpensesNo" slot-scope="text, record">
          <span :class="$hasPermissions('B_expenseDetail')?'active':'common'" @click="handleDetail(record)">{{ text }}</span>
        </template>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
            size="small"
            type="link"
            v-if="record.state == 'WAIT_AUDIT' && $hasPermissions('B_expenseAudit')"
            class="button-warring"
            @click="handleAudit(record)"
            id="expenseManagement-audit-btn">审核</a-button>
          <a-button
            size="small"
            type="link"
            v-if="record.state == 'WAIT_AUDIT' && $hasPermissions('B_expenseEdit')"
            class="button-info"
            @click="handleEdit(record)"
            id="expenseManagement-edit-btn">编辑</a-button>
          <a-button
            size="small"
            type="link"
            v-if="record.state == 'WAIT_AUDIT' && $hasPermissions('B_expenseDel')"
            class="button-error"
            @click="handleDel(record)"
            id="expenseManagement-del-btn">删除</a-button>
          <span v-if="record.state != 'WAIT_AUDIT'||( !$hasPermissions('B_expenseAudit')&& !$hasPermissions('B_expenseEdit') && !$hasPermissions('B_expenseDel'))">--</span>
        </template>
      </s-table>
    </a-spin>
    <!-- 详情 -->
    <expense-management-detail-modal :openModal="openModal" :itemId="itemId" @close="closeDetail" />
  </a-card>
</template>

<script>
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import { settleExpenseQuery, delExpense, settleExpenseQuerySum, auditExpense } from '@/api/settleExpense'
import { costTypeAllQuery } from '@/api/costType'
import expenseManagementDetailModal from './detailModal.vue'
export default {
  components: { STable, VSelect, expenseManagementDetailModal, rangeDate },
  data () {
    return {
      spinning: false,
      tableHeight: 0,
      disabled: false, //  查询、重置按钮是否可操作
      advanced: false, //  高级搜索 展开/关闭
      costTypeList: [], // 费用类型
      costType: [],
      // 查询参数
      queryParam: {
        beginDate: '',
        endDate: '',
        accountExpensesNo: '',
        expensesTypeSn1: '',
        expensesTypeSn2: '',
        expensesTypeSn3: '',
        state: '',
        settleState: ''
      },
      // 汇总
      totalData: {
        count: 0,
        totalAmount: 0
      },
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: 80, align: 'center' },
        { title: '费用单号', dataIndex: 'accountExpensesNo', width: 250, align: 'center', scopedSlots: { customRender: 'accountExpensesNo' } },
        { title: '创建时间', dataIndex: 'createDate', width: 160, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '费用类型', align: 'center', scopedSlots: { customRender: 'expensesType' } },
        { title: '金额', dataIndex: 'settleAmount', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? ('￥' + text) : '--') } },
        { title: '单据状态', dataIndex: 'stateDictValue', width: 110, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 200, align: 'center', fixed: 'right' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        if (this.tableHeight == 0) {
          this.tableHeight = window.innerHeight - 300
        }
        return settleExpenseQuery(Object.assign(parameter, this.queryParam)).then(res => {
          const 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
          }
          this.disabled = false
          // 费用类型
          if (this.costTypeList.length == 0) {
            this.getCostTypeList()
          }
          // 汇总
          this.totalData.count = data.count
          this.settleExpenseQuerySum(Object.assign(parameter, this.queryParam))
          return data
        })
      },
      openModal: false, //  查看详情  弹框
      itemId: '' //  当前id
    }
  },
  methods: {
    //  时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    //  递归函数
    recursionFun (data) {
      if (data) {
        data.map((item, index) => {
          if (item.children && item.children.length == 0) {
            delete item.children
          } else {
            this.recursionFun(item.children)
          }
        })
      }
    },
    // 获取费用类型数据
    getCostTypeList () {
      costTypeAllQuery({}).then(res => {
        //  递归去除空children
        this.recursionFun(res.data)
        this.costTypeList = res.data
      })
    },
    closeDetail () {
      this.openModal = false
      this.itemId = null
    },
    //  费用类型  change
    changeCostType (val, opt) {
      this.queryParam.expensesTypeSn1 = val[0] ? val[0] : ''
      this.queryParam.expensesTypeSn2 = val[1] ? val[1] : ''
      this.queryParam.expensesTypeSn3 = val[2] ? val[2] : ''
    },
    //  新增/编辑
    handleEdit (row) {
      if (row) {
        this.$router.push({ name: 'expenseManagementEdit', params: { id: row.id } })
      } else {
        this.$router.push({ name: 'expenseManagementAdd' })
      }
    },
    //  详情
    handleDetail (row) {
      if (this.$hasPermissions('B_expenseDetail')) {
        this.itemId = row.id
        this.openModal = true
      }
    },
    //  审核
    handleAudit (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确定要审核吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          auditExpense({
            id: row.id
          }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    //  删除
    handleDel (row) {
      const _this = this
      _this.itemId = row.id
      _this.$confirm({
        title: '提示',
        content: '删除后原数据不可恢复，是否删除？',
        centered: true,
        onOk () {
          _this.spinning = true
          delExpense({ id: _this.itemId }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 汇总
    settleExpenseQuerySum (params) {
      settleExpenseQuerySum(params).then(res => {
        this.totalData.totalAmount = res.data && res.data.settleAmount || 0
      })
    },
    //  重置
    resetSearchForm () {
      this.$refs.rangeDate.resetDate()
      this.queryParam.beginDate = ''
      this.queryParam.endDate = ''
      this.queryParam.accountExpensesNo = ''
      this.queryParam.expensesTypeSn1 = ''
      this.queryParam.expensesTypeSn2 = ''
      this.queryParam.expensesTypeSn3 = ''
      this.queryParam.state = ''
      this.queryParam.settleState = ''
      this.queryParam.beginDate = ''
      this.queryParam.endDate = ''
      this.costType = []
      this.$refs.table.refresh(true)
    }
  }
}
</script>
<style lang="less">
  .expenseManagementList-wrap{
    .sTable{
      margin-top: 15px;
    }
	.active{
		color: #ed1c24;
		cursor: pointer;
	}
	.common{
		color: rgba(0, 0, 0, 0.65);
	}
  }
</style>
