<template>
  <div class="app-container">
    <div v-show="isShow">
      <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="68px">
        <el-form-item label="系统单号" prop="sysNo">
          <el-input
              v-model="queryParams.sysNo"
              clearable
              placeholder="请输入系统单号"
              size="small"
              @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="开票日期" prop="timeInterval">
          <el-date-picker
              v-model="queryParams.timeInterval"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="至"
              start-placeholder="开始月份"
              end-placeholder="结束月份"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="客户名称" label-width="120px" prop="fCorpid">
          <el-select v-model="queryParams.fCorpid" clearable filterable
                     placeholder="请选择客户"
          >
            <el-option
                v-for="item in fCorpList"
                :key="item.fId"
                :label="item.fName"
                :value="item.fId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目名称" label-width="120px" prop="fGoodsid">
          <el-select v-model="queryParams.fGoodsid" clearable
                     filterable placeholder="请选择项目"
          >
            <el-option
                v-for="item in fGoodsList"
                :key="item.fId"
                :label="item.projectName"
                :value="item.fId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" size="mini" type="cyan" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
              icon="el-icon-plus"
              size="mini"
              type="primary"
              @click="handleAdd"
          >新单
          </el-button>
        </el-col>
        <!--        <el-col :span="1.5">-->
        <!--          <el-button-->
        <!--            v-hasPermi="['warehouse:fee:edit']"-->
        <!--            :disabled="single"-->
        <!--            icon="el-icon-edit"-->
        <!--            size="mini"-->
        <!--            type="success"-->
        <!--            @click="handleUpdate"-->
        <!--          >修改-->
        <!--          </el-button>-->
        <!--        </el-col>-->
        <!--        <el-col :span="1.5">-->
        <!--          <el-button-->
        <!--            v-hasPermi="['warehouse:fee:remove']"-->
        <!--            :disabled="multiple"-->
        <!--            icon="el-icon-delete"-->
        <!--            size="mini"-->
        <!--            type="danger"-->
        <!--            @click="handleDelete"-->
        <!--          >删除-->
        <!--          </el-button>-->
        <!--        </el-col>-->
        <!--        <el-col :span="1.5">-->
        <!--          <el-button-->
        <!--            v-hasPermi="['warehouse:fee:export']"-->
        <!--            icon="el-icon-download"-->
        <!--            size="mini"-->
        <!--            type="warning"-->
        <!--            @click="handleExport"-->
        <!--          >导出-->
        <!--          </el-button>-->
        <!--        </el-col>-->
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <el-table v-loading="loading" show-summary :summary-method="getSummaries" :data="feeList" @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" width="55"/>
        <el-table-column align="center" label="系统单号" prop="sysNo"/>
        <el-table-column align="center" label="开票日期" prop="kpTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.kpTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="客户名称" prop="fCorpid"/>
        <el-table-column align="center" label="项目名称" prop="fGoodsid"/>
        <el-table-column align="center" label="金额合计" prop="sumMoney"/>
        <el-table-column align="center" label="发票号" prop="invoiceNo"/>
        <el-table-column align="center" label="开票公司" prop="fSbu"/>
        <el-table-column align="center" label="发票类型" prop="invoiceType"/>
        <el-table-column align="center" label="制单人" prop="createBy"/>
        <el-table-column align="center" label="制单日期" prop="createTime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="备注" prop="remark"/>
        <el-table-column align="center" label="付款金额" prop="proceeds"/>
        <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
          <template slot-scope="scope">
            <el-button
                v-hasPermi="['warehouse:fee:edit']"
                icon="el-icon-edit"
                size="mini"
                type="text"
                @click="handleUpdate(scope.row)"
            >修改
            </el-button>
            <el-button
                v-hasPermi="['warehouse:fee:remove']"
                icon="el-icon-delete"
                size="mini"
                type="text"
                @click="handleDelete(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :limit.sync="queryParams.pageSize"
          :page.sync="queryParams.pageNum"
          :total="total"
          :page-sizes="[10, 20, 30, 50, 100, 200, 300, 400]"
          @pagination="getList"
      />
    </div>
    <detailPage v-if="!isShow" ref="detail" :detailData="detailData" @goBack="goBack"></detailPage>
  </div>
</template>

<script>
import { delInvoice, listInvoice } from '@/api/invoice/invoice'
import { company, queryItem } from '@/api/purchaseIssue/index'
import detailPage from './detailsPage'

export default {
  name: 'Fee',
  components: { detailPage },
  data() {
    return {
      isShow: true,
      detailData: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 财务数据主表格数据
      feeList: [],
      fCorpList: [],
      fGoodsList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: 1
      },
      // 表单参数
      form: {},
      fCorpMap: {},
      fSbuMap: {},
      fGoodsMap: {},
      invoiceTypeList: [],
      // 表单校验
      rules: {
        fBilltype: [
          {
            required: true,
            message: '单据类型(对账单 收费 付费 付费申请 收费申请，发票申请 销项发票 进项发票)不能为空',
            trigger: 'change'
          }
        ],
        fDeptid: [
          { required: true, message: '制单部门不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getDicts('invoice_type').then(response => {
      this.invoiceTypeList = response.data
    })
    company(3).then(res => {
      this.fCorpList = res.data
      for (var index in res.data) {
        this.fCorpMap[res.data[index].fId] = res.data[index].fName
      }
    })
    // 开票公司
    company(2).then(res => {
      for (var index in res.data) {
        this.fSbuMap[res.data[index].fId] = res.data[index].fName
      }
    })
    // 项目名称
    queryItem().then(res => {
      this.fGoodsList = res.data
      for (var index in res.data) {
        this.fGoodsMap[res.data[index].fId] = res.data[index].projectName
      }
    })
    this.$nextTick(_ => {
      this.getList()
    })
  },
  methods: {
    goBack() {
      this.getList()
      this.detailData = {}
      this.isShow = true
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (column.property === 'sumMoney' || column.property === 'proceeds') {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return Math.round(prev + curr * 100) / 100;
            } else {
              return Math.round(prev * 100) / 100;
            }
          }, 0);
          sums[index];

        }
      });
      return sums
    },
    /** 查询财务数据主列表 */
    getList() {
      this.loading = true
      listInvoice(this.queryParams).then(response => {
        this.feeList = response.rows
        this.feeList.forEach(data => {
          // 客户
          data.fCorpid = this.fCorpMap[data.fCorpid]
          // 项目
          data.fGoodsid = this.fGoodsMap[data.fGoodsid]
          // 开票
          data.fSbu = this.fSbuMap[data.fSbu]

          this.invoiceTypeList.forEach(datas => {
            if (datas.dictSort == data.invoiceType) {
              data.invoiceType = datas.dictLabel
            }
          })
        })
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        fId: null,
        fBillno: null,
        fActId: null,
        fCtrlcorpid: null,
        fTransActId: null,
        fCorpid: null,
        tMblno: null,
        fAmtdr: null,
        fAmtcr: null,
        fFromDate: null,
        fToDate: null,
        fRefNo: null,
        fBilltype: null,
        fBillstatus: '0',
        fRemarks: null,
        fAccbilldate: null,
        delFlag: null,
        createBy: null,
        fDeptid: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        chargingMethod: null,
        invoiceNo: null,
        bank: null,
        waterBillNo: null,
        fSystemType: null,
        fTrackingNumber: null,
        fInvoiceRise: null,
        fSign: null,
        fSendTime: null,
        fApplyMoney: null,
        fAccountId: null,
        fMake: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {

      this.detailData = {}
      this.isShow = false
      // this.reset()
      // this.open = true
      // this.title = '添加财务数据主'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.detailData = {
        id: row.id
      }
      this.isShow = false
      // this.isShow = false;
      // this.reset()
      // const fId = row.fId || this.ids
      // getFee(fId).then(response => {
      //   this.form = response.data
      //   this.open = true
      //   this.title = '修改财务数据主'
      // })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.fId != null) {
            updateFee(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addFee(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if (row.kpType == 2) {
        this.$message({
          message: '已开票无法删除',
          type: 'warning'
        });
        return
      }
      const fIds = row.fId || this.ids
      this.$confirm('是否确认删除?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delInvoice(row.id)
      }).then((res) => {
        if (res.code == 200) {
          this.msgSuccess('删除成功')
          this.$message({
            message: '删除成功',
            type: 'success'
          })
        } else {
          this.$message.error(res.msg)
        }
        this.getList()
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有财务数据主数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return exportFee(queryParams)
      }).then(response => {
        this.download(response.msg)
      })
    }
  }
}
</script>
