<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form v-show="status=='0' || status=='3'" :inline="true" class="demo-form-inline">
        <el-form-item>
          <el-button icon="el-icon-plus" size="small" plain type="primary" @click="dialogStartVisible=true">
            {{ status=='0'?"开始对账":"导入帐单" }}
          </el-button>
          <el-button icon="el-icon-s-grid" size="small" plain @click="dialogBatchInput=true">
            导入已核对费用
          </el-button>
        </el-form-item>
      </el-form>
      <el-form :inline="true" size="small" :model="formReconcile">
        <el-form-item label="结算周期:">
          <xyyEnum
            style="width: 120px;"
            :model.sync="formReconcile.billingCycle"
            title="结算周期"
            enum-name="BillingCycle"
            get-enum="GetDes"
          />
        </el-form-item>
        <el-form-item label="客户">
          <el-select
            v-model="formReconcile.customerId"
            placeholder="客户"
            clearable
            filterable
            style="width: 160px;"
          >
            <el-option
              v-for="item in Customers"
              :key="item.Id"
              :label="item.CompanyName"
              :value="item.Id"
            />
          </el-select>
        </el-form-item>
      <el-form-item> 
        <el-select v-model="formReconcile.IsInterceptCustomers" placeholder="欠费拦截状态" clearable filterable>
          <el-option label="拦截" value="True" />
          <el-option label="不拦截" value="False" />
        </el-select>
      </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchReconcile" :loading="searchLoading">查询</el-button>
          <el-select v-model="billingCycle" placeholder="报表类型" style="width: 150px; margin: 0 10px;">
            <el-option label="系统帐(合并渠道)" :value="1" />
          </el-select>
          <el-button type="success" @click="batchReconcile">批量下载</el-button>
        </el-form-item>
      </el-form>
      <el-tabs type="card" value="1" @tab-click="tab_cliek">
        <el-tab-pane name="1">
          <span slot="label">
            待对帐
            <el-badge :value="s1" class="item" />
          </span>
          <el-table :data="s1Data" border @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="帐单名称" prop="Name" />
            <el-table-column label="客户" prop="CustomerName" />
      <el-table-column label="拦截欠费" prop="IsInterceptCustomers">
        <template slot-scope="r">
          <el-tag v-if="r.row.IsInterceptCustomers">是</el-tag>
          <el-tag v-if="!r.row.IsInterceptCustomers" type="info">否</el-tag> 
        </template>
        </el-table-column>
            <el-table-column label="重量">
              <template slot-scope="scope">
                <el-tag> 我方{{ scope.row.SysWeight }}KG</el-tag>
                <el-tag>对方{{ scope.row.ServiceWeight }}KG</el-tag>
                <el-tag type="danger">差异{{ (scope.row.SysWeight-scope.row.ServiceWeight).toFixed(3) }}KG</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="金额">
              <template slot-scope="scope">
                <el-tag> 我方{{ scope.row.SysFreigh }}</el-tag>
                <el-tag>对方{{ scope.row.ServiceFreigh }}</el-tag>
                <el-tag type="danger">未确认{{ (scope.row.NotConfirmedFreigh) }}</el-tag>
                <el-tag type="success">确认{{ (scope.row.ConfirmedFreigh) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="补扣款">
              <template slot-scope="scope">
                <el-tag> 补款{{ scope.row.Supplement }}</el-tag>
                <el-tag type="danger">扣款{{ scope.row.Deduction }}</el-tag>
                <el-tag type="warning">索赔{{ scope.row.ClaimAmount?scope.row.ClaimAmount:0 }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="状态" width="78">
              <template slot-scope="scope">
                <el-tag :type="billStateTagType(scope.row.BillState)">
                  {{ scope.row.BillState | getBillStateText }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              label="更新时间"
              prop="UpdateTime"
              width="200"
            />
            <el-table-column label="操作" width="390">
              <template slot-scope="scope">
                <el-dropdown @command="handleCommand">
                  <el-button size="mini">
                    运费<i class="el-icon-arrow-down el-icon--right" />
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command="'getYCSystemBillSplie_'+scope.row.Id">系统帐(YC模板)</el-dropdown-item>
                    <el-dropdown-item :command="'getSystemBillMange_'+scope.row.Id">系统帐(合并渠道)</el-dropdown-item>
                    <el-dropdown-item :command="'getSystemBillSplie_'+scope.row.Id">系统帐(分开渠道)</el-dropdown-item>
                    <el-dropdown-item :command="'getOriginals_'+scope.row.Id">帐单数据</el-dropdown-item>
                    <el-dropdown-item :command="'getNotConfirmeds_'+scope.row.Id">未确认数据</el-dropdown-item>
                    <el-dropdown-item :command="'getConfirmeds_'+scope.row.Id">已确认数据</el-dropdown-item>
                    <el-dropdown-item :command="'inputWeight_'+scope.row.Id">导入重量</el-dropdown-item>
                    <el-dropdown-item :command="'setNotConfirmeds_'+scope.row.Id">处理差异</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <el-dropdown @command="handleCommand">
                  <el-button size="mini">
                    补扣款<i class="el-icon-arrow-down el-icon--right" />
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command="'getSupplements_'+scope.row.Id">补款信息</el-dropdown-item>
                    <el-dropdown-item :command="'getDeductions_'+scope.row.Id">扣款信息</el-dropdown-item>
                    <el-dropdown-item :command="'getClaims_'+scope.row.Id">索赔信息</el-dropdown-item>
                    <el-dropdown-item :command="'setSupplements_'+scope.row.Id">处理补款</el-dropdown-item>
                    <el-dropdown-item :command="'setDeductions_'+scope.row.Id">处理扣款</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <el-button size="mini" type="success" @click="setPassBill(scope.row.Id)">
                  通过
                </el-button>
                <el-button size="mini" type="primary" @click="rerunBill(scope.row)">
                  重新生成
                </el-button>
                <el-button size="mini" type="danger" @click="deleteBill(scope.row.Id)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane name="3">
          <span slot="label">
            最终确认
            <el-badge :value="s3" class="item" />
          </span>
          <el-table :data="s3Data" border>
            <el-table-column label="帐单名称" prop="Name" />
            <el-table-column label="客户" prop="CustomerName" />
      <el-table-column label="拦截欠费" prop="IsInterceptCustomers">
        <template slot-scope="r">
          <el-tag v-if="r.row.IsInterceptCustomers">是</el-tag>
          <el-tag v-if="!r.row.IsInterceptCustomers" type="info">否</el-tag> 
        </template>
        </el-table-column>
            <el-table-column label="重量">
              <template slot-scope="scope">
                <el-tag> 我方{{ scope.row.SysWeight }}KG</el-tag>
                <el-tag>对方{{ scope.row.ServiceWeight }}KG</el-tag>
                <el-tag type="danger">差异{{ (scope.row.SysWeight-scope.row.ServiceWeight).toFixed(3) }}KG</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="金额">
              <template slot-scope="scope">
                <el-tag> 我方{{ scope.row.SysFreigh }}</el-tag>
                <el-tag>对方{{ scope.row.ServiceFreigh }}</el-tag>
                <el-tag type="danger">未确认{{ (scope.row.NotConfirmedFreigh) }}</el-tag>
                <el-tag type="success">确认{{ (scope.row.ConfirmedFreigh) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="补扣款">
              <template slot-scope="scope">
                <el-tag> 补款{{ scope.row.Supplement }}</el-tag>
                <el-tag type="danger">扣款{{ scope.row.Deduction }}</el-tag>
                <el-tag type="warning">索赔{{ scope.row.ClaimAmount?scope.row.ClaimAmount:0 }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              label="更新时间"
              prop="UpdateTime"
              width="200"
            />
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-dropdown @command="handleCommand">
                  <el-button size="mini">
                    运费<i class="el-icon-arrow-down el-icon--right" />
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command="'getOriginals_'+scope.row.Id">帐单数据</el-dropdown-item>
                    <el-dropdown-item :command="'getNotConfirmeds_'+scope.row.Id">未确认数据</el-dropdown-item>
                    <el-dropdown-item :command="'getConfirmeds_'+scope.row.Id">已确认数据</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <el-dropdown @command="handleCommand">
                  <el-button size="mini">
                    补扣款<i class="el-icon-arrow-down el-icon--right" />
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command="'getSupplements_'+scope.row.Id">补款信息</el-dropdown-item>
                    <el-dropdown-item :command="'getDeductions_'+scope.row.Id">扣款信息</el-dropdown-item>
                    <el-dropdown-item :command="'getClaims_'+scope.row.Id">索赔信息</el-dropdown-item>
                    <el-dropdown-item :command="'setClaims_'+scope.row.Id">处理索赔</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <el-button size="mini" type="success" @click="setPassBill(scope.row.Id)">
                  通过
                </el-button>
                <el-button size="mini" type="warning" @click="setRejectBill(scope.row.Id)">
                  驳回
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane name="4">
          <span slot="label">
            收款中
            <el-badge :value="s4" class="item" />
          </span>
          <el-table :data="s4Data" border>
            <el-table-column label="帐单名称" prop="Name" />
            <el-table-column label="客户" prop="CustomerName" />
      <el-table-column label="拦截欠费" prop="IsInterceptCustomers">
        <template slot-scope="r">
          <el-tag v-if="r.row.IsInterceptCustomers">是</el-tag>
          <el-tag v-if="!r.row.IsInterceptCustomers" type="info">否</el-tag> 
        </template>
        </el-table-column>
            <el-table-column label="重量">
              <template slot-scope="scope">
                <el-tag> 我方{{ scope.row.SysWeight }}KG</el-tag>
                <el-tag>对方{{ scope.row.ServiceWeight }}KG</el-tag>
                <el-tag type="danger">差异{{ (scope.row.SysWeight-scope.row.ServiceWeight).toFixed(3) }}KG</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="金额">
              <template slot-scope="scope">
                <el-tag> 我方{{ scope.row.SysFreigh }}</el-tag>
                <el-tag>对方{{ scope.row.ServiceFreigh }}</el-tag>
                <el-tag type="danger">未确认{{ (scope.row.NotConfirmedFreigh) }}</el-tag>
                <el-tag type="success">确认{{ (scope.row.ConfirmedFreigh) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="补扣款">
              <template slot-scope="scope">
                <el-tag> 补款{{ scope.row.Supplement }}</el-tag>
                <el-tag type="danger">扣款{{ scope.row.Deduction }}</el-tag>
                <el-tag type="warning">索赔{{ scope.row.ClaimAmount?scope.row.ClaimAmount:0 }}</el-tag>

              </template>
            </el-table-column>
            <el-table-column
              label="最终金额"
            >
              <template slot-scope="scope">
                <el-tag type="info">应收 {{ scope.row.Receivables }} RMB</el-tag>
                <el-tag>已收 {{ scope.row.Payment }} RMB</el-tag>
              </template>
            </el-table-column>

            <el-table-column
              label="更新时间"
              prop="UpdateTime"
              width="200"
            />
            <el-table-column label="操作" width="250">
              <template slot-scope="scope">
                <el-dropdown @command="handleCommand">
                  <el-button size="mini">
                    帐单<i class="el-icon-arrow-down el-icon--right" />
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command="'getOriginals_'+scope.row.Id">帐单数据</el-dropdown-item>
                    <el-dropdown-item :command="'getNotConfirmeds_'+scope.row.Id">未确认数据</el-dropdown-item>
                    <el-dropdown-item :command="'getConfirmeds_'+scope.row.Id">已确认数据</el-dropdown-item>
                    <el-dropdown-item :command="'getSupplements_'+scope.row.Id">补款信息</el-dropdown-item>
                    <el-dropdown-item :command="'getDeductions_'+scope.row.Id">扣款信息</el-dropdown-item>
                    <el-dropdown-item :command="'getClaims_'+scope.row.Id">索赔信息</el-dropdown-item>

                  </el-dropdown-menu>
                </el-dropdown>
                <el-dropdown @command="handleCommand">
                  <el-button size="mini">
                    收款<i class="el-icon-arrow-down el-icon--right" />
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command="'setPayment_'+scope.row.Id">收款</el-dropdown-item>
                    <el-dropdown-item :command="'getPaymentLog_'+scope.row.Id">收款明细</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <el-button size="mini" type="warning" @click="setRejectBill(scope.row.Id)">
                  驳回
                </el-button>
                <el-button size="mini" type="danger" @click="deleteBill(scope.row.Id)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane name="5">
          <span slot="label">
            已收款
            <el-badge :value="s5" class="item" />
          </span>
          <el-table :data="s5Data" border>
            <el-table-column label="帐单名称" prop="Name" />
            <el-table-column label="客户" prop="CustomerName" />
      <el-table-column label="拦截欠费" prop="IsInterceptCustomers">
        <template slot-scope="r">
          <el-tag v-if="r.row.IsInterceptCustomers">是</el-tag>
          <el-tag v-if="!r.row.IsInterceptCustomers" type="info">否</el-tag> 
        </template>
        </el-table-column>
            <el-table-column label="重量">
              <template slot-scope="scope">
                <el-tag> 我方{{ scope.row.SysWeight }}KG</el-tag>
                <el-tag>对方{{ scope.row.ServiceWeight }}KG</el-tag>
                <el-tag type="danger">差异{{ (scope.row.SysWeight-scope.row.ServiceWeight).toFixed(3) }}KG</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="金额">
              <template slot-scope="scope">
                <el-tag> 我方{{ scope.row.SysFreigh }}</el-tag>
                <el-tag>对方{{ scope.row.ServiceFreigh }}</el-tag>
                <el-tag type="danger">未确认{{ (scope.row.NotConfirmedFreigh) }}</el-tag>
                <el-tag type="success">确认{{ (scope.row.ConfirmedFreigh) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="补扣款">
              <template slot-scope="scope">
                <el-tag> 补款{{ scope.row.Supplement }}</el-tag>
                <el-tag type="danger">扣款{{ scope.row.Deduction }}</el-tag>
                <el-tag type="warning">索赔{{ scope.row.ClaimAmount?scope.row.ClaimAmount:0 }}</el-tag>

              </template>
            </el-table-column>
            <el-table-column
              label="最终金额"
            >
              <template slot-scope="scope">
                <el-tag type="info">应收 {{ scope.row.Receivables }} RMB</el-tag>
                <el-tag>已收 {{ scope.row.Payment }} RMB</el-tag>
              </template>
            </el-table-column>

            <el-table-column
              label="更新时间"
              prop="UpdateTime"
              width="200"
            />
            <el-table-column label="操作" width="250">
              <template slot-scope="scope">
                <el-dropdown @command="handleCommand">
                  <el-button size="mini">
                    帐单<i class="el-icon-arrow-down el-icon--right" />
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command="'getOriginals_'+scope.row.Id">帐单数据</el-dropdown-item>
                    <el-dropdown-item :command="'getNotConfirmeds_'+scope.row.Id">未确认数据</el-dropdown-item>
                    <el-dropdown-item :command="'getConfirmeds_'+scope.row.Id">已确认数据</el-dropdown-item>
                    <el-dropdown-item :command="'getSupplements_'+scope.row.Id">补款信息</el-dropdown-item>
                    <el-dropdown-item :command="'getDeductions_'+scope.row.Id">扣款信息</el-dropdown-item>
                    <el-dropdown-item :command="'getClaims_'+scope.row.Id">索赔信息</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <el-button size="mini" @click="handleCommand('getPaymentLog_'+scope.row.Id)">
                  收款明细
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>

    <el-dialog
      title="提示"
      :visible.sync="dialogConfirmVisible"
      width="30%"
    >
      <span>是否确定通过该帐单</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogConfirmVisible = false">取 消</el-button>
        <el-button type="primary" @click="postPass">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="提示"
      :visible.sync="dialogRejectVisible"
      width="30%"
    >
      <span>是否确定驳回该帐单</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogRejectVisible = false">取 消</el-button>
        <el-button type="primary" @click="postReject">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="处理差异" :visible.sync="dialogNotConfirmed">
      <el-form label-width="80px">
        <el-form-item label="确认文件">
          <el-upload
            class="upload-demo"
            :action="`${apiAddress}/api/Finance/updateLoadFile`"
            :on-success="changeTempUrl"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传excel文件
              <el-link type="primary" @click="handleCommand('getNotConfirmeds_'+billId)">待处理差异</el-link>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogNotConfirmed = false">取 消</el-button>
        <el-button type="primary" @click="postConfirmed">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="feeType==1?'扣款': feeType==2? '补款':'导入重量'" :visible.sync="dialogInputSupplementOrDeduction">
      <el-form label-width="80px">
        <el-form-item label="确认文件">
          <el-upload
            class="upload-demo"
            :action="`${apiAddress2}/api/Finance/updateLoadFile`"
            :on-success="changeTempUrl"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传excel文件
              <el-link v-if="feeType<2" type="primary" @click="feeType==1? handleCommand('getDeductions_'+billId):handleCommand('getSupplements_'+billId)">已处理数据</el-link>
              <el-link type="primary" @click="handleCommand('getOriginals_'+billId)">帐单明细</el-link>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click=" dialogInputSupplementOrDeduction= false">取 消</el-button>
        <el-button type="primary" @click="postSupplementOrDeduction">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="收款明细" :visible.sync="dialogFees">
      <el-table :data="PaymentData" border>
        <el-table-column label="收款时间" prop="CreateTime" />
        <el-table-column label="原已收款" prop="OldPayment" />
        <el-table-column label="收款金额" prop="Payment" />
        <el-table-column label="新已收款" prop="NewPayment" />
      </el-table>
    </el-dialog>

    <el-dialog title="收款" :visible.sync="dialogPaymentVisible">
      <el-form :model="row" label-width="80px">
        <el-form-item label="收款金额">
          <el-input v-model="postPaymentFee" min="0" autocomplete="off" />  RMB
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPaymentVisible = false">取 消</el-button>
        <el-button type="primary" @click="postPayment">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="`索赔 (${currentClaimBill==null?'':currentClaimBill.Name})`" :visible.sync="dialogClaimVisible">
      <el-form>
        <el-form-item label="财务确认时间">
          <el-date-picker
            v-model="claimTimeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right"><el-button :loading="handlingClaim" type="success" @click="computeClaim">计算索赔</el-button></div>
    </el-dialog>

    <el-dialog title="开始对帐" :visible.sync="dialogStartVisible">
      <el-form :model="createDto" label-width="80px">
        <el-form-item v-if="status=='0'" label="帐单名称">
          <el-input v-model="createDto.Name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="客户">
          <el-select v-model="createDto.CustomerId" placeholder="请选择" filterable>
            <el-option
              v-for="item in Customers"
              :key="item.Id"
              :label="item.CustomerNumber"
              :value="item.Id"
            >
              <span style="float: left">{{ item.CompanyName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.CustomerNumber }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="status=='0'" label="发货时间">
          <div class="block">
            <el-date-picker
              v-model="createDto.DelvieryDate"
              type="daterange"

              range-separator="至"
              start-placeholder="开始日期"
              value-format="yyyy-MM-dd"
              end-placeholder="结束日期"
            />
          </div>
        </el-form-item>
        <el-form-item v-if="status==3" label="帐单文件">
          <el-upload
            class="upload-demo"
            :action="`${apiAddress}/api/Finance/updateLoadFile`"
            :on-success="changeCreateBillUrl"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogStartVisible = false">取 消</el-button>
        <el-button type="primary" @click="postStart">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="导入已核对费用" :visible.sync="dialogBatchInput">
      <el-form>
        <el-form-item label="明细文件">
          <el-upload
            class="upload-demo"
            :action="`${apiAddress}/api/Finance/updateLoadFile`"
            :on-success="changeFileUrl"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传zip文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogBatchInput = false">取 消</el-button>
        <el-button type="primary" @click="start">开始任务</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { _getQtys, _getPostData, _getConfirmeds, _getNotConfirmeds, _getOriginals, _getSupplements
  , _getDeductions, _addDeliveryBill, _inputSupplementOrDeduction, _updateConfirmed, _Pass, _Rereject
  , _postPayment, _getPaymentLog, _deleteBill, _addDeliveryBillAsFile, _computeBillClaimemAmount, _getClaims
  , _getOutCustomer
  , _getOutYCCustomer,
  _ReProcessDeliveryBill,
  _getOutCustomerBatch
}
from '@/api/financeCustomerDelivery'
import { _getCustomers, _getChannel } from '@/api/baseInfo'
import { Loading } from 'element-ui'
import xyyEnum from '@/components/Xyy/Enums/enums'

const apiAddress = 'http://wms.xingyunyi.cn'
const apiAddress2 = 'http://120.24.149.148'
// 状态
const billState = new Map([
  [0, '新增'],
  [1, '完成'],
  [2, '异常'],
  [3, '重跑中']
])
const billStateTagType = new Map([
  [0, ''],
  [1, 'success'],
  [2, 'danger'],
  [3, 'warning']
])

export default {
  name: 'Customer',
  filters: {
    // 状态文字显示
    getBillStateText(val) {
      return billState.get(val) || '-'
    }
  },
  components: { xyyEnum },
  data() {
    return {
      apiAddress: apiAddress,
      apiAddress2: apiAddress2,
      fileUrl: '',
      dialogBatchInput: false,
      addAsFile: false,
      dialogFees: false,
      dialogPaymentVisible: false,
      claimTimeRange: null,
      dialogClaimVisible: false,
      currentClaimBill: null,
      handlingClaim: false,
      s1: 0,
      s2: 0,
      s3: 0,
      s4: 0,
      s5: 0,
      dialogNotConfirmed: false,
      dialogInputSupplementOrDeduction: false,
      dialogStartVisible: false,
      dialogConfirmVisible: false,
      dialogRejectVisible: false,
      status: '0',
      createDto: {
        Name: '',
        Curreny: '',
        ServiceBillUrl: '',
        DelvieryDate: [],
        CustomerId: 1,
        StartTime: '',
        EndTime: ''
      },
      s1Data: [],
      s2Data: [],
      s3Data: [],
      s4Data: [],
      s5Data: [],
      billId: 0,
      tempUrl: '',
      feeType: 1,
      row: {},
      Customers: [{ CompanyName: '澳鹏', Id: 7 }],
      Channels: [],
      PaymentData: [],
      postPaymentFee: 0,
      formReconcile: {
        billingCycle: undefined,
        customerId: undefined
      },
      billingCycle: 1,
      searchLoading: true,
      billIdList: []
    }
  },
  created() {
    var that = this
    _getCustomers().then(response => {
      that.Customers = response
      _getChannel().then(response => {
        that.Channels = response
        that.getdata()
      })
    })
  },
  methods:
  {
    changeFileUrl(r) {
      this.fileUrl = r.Data.url
    },
    start() {
      if (this.$store.getters.isConnection) {
        this.$alert('已开始任务，任务详情点击右上角任务图标')
        this.$store.getters.connection.invoke('Start', this.fileUrl).then(() => {
        }).catch(r => {
          this.$alert('开始任务失败' + r)
        })
        this.dialogBatchInput = false
      } else {
        this.$alert('当前webSocket未连接')
      }
    },
    tab_cliek(t) {
      this.status = t.name - 1
      this.getdata()
    },
    deleteBill(id) {
      this.$confirm('是否确认删除帐号?').then(response => {
        _deleteBill({ billId: id }).then(response => {
          this.getdata()
        })
      })
    },
    handleCommand(command) {
      var action = command.split('_')[0]
      this.billId = command.split('_')[1]
      if (action == 'getOriginals') {
        _getOriginals(this.billId)
      } else if (action == 'getConfirmeds') {
        _getConfirmeds(this.billId)
      } else if (action == 'getNotConfirmeds') {
        _getNotConfirmeds(this.billId)
      } else if (action == 'getSupplements') {
        _getSupplements(this.billId)
      } else if (action == 'getDeductions') {
        _getDeductions(this.billId)
      } else if (action == 'getClaims') {
        _getClaims(this.billId)
      } else if (action == 'setNotConfirmeds') {
        this.setNotConfirmeds()
      } else if (action == 'setSupplements') {
        this.feeType = 2
        this.setInputSupplementOrDeduction()
      } else if (action == 'setDeductions') {
        this.feeType = 1
        this.setInputSupplementOrDeduction()
      } else if (action == 'setPayment') {
        this.setPayment()
      } else if (action == 'getPaymentLog') {
        this.getPaymentLog()
      } else if (action === 'inputWeight') {
        // 导入重量
        this.feeType = 3
        this.setInputSupplementOrDeduction()
      } else if (action == 'setClaims') {
        this.setClaims()
      } else if (action == 'getSystemBillMange') {
        _getOutCustomer(this.billId, 1)
      } else if (action == 'getSystemBillSplie') {
        _getOutCustomer(this.billId, 2)
      } else if (action == 'getYCSystemBillSplie') {
        _getOutYCCustomer(this.billId, 1)
      }

      // this.$message('click on item ' + command);
    },
    computeClaim() {
      const billId = this.billId

      if (!billId) {
        this.$message('账单ID无效')
        return
      } else if (!this.claimTimeRange || this.claimTimeRange.length < 2) {
        this.$message('请选择时间范围')
        return
      }
      this.handlingClaim = true
      const that = this
      const from = this.claimTimeRange[0]
      const to = this.claimTimeRange[1]
      const data = { billId, from, to }
      _computeBillClaimemAmount(data).then(resp => {
        if (resp.success == true) {
          this.$message('操作成功')
          setTimeout(() => {
            that.dialogClaimVisible = false
          }, 2000)
        } else {
          const msg = resp.Message
          this.$message(msg)
        }
      }).finally(() => {
        this.handlingClaim = false
      })
    },
    postPayment() {
      _postPayment({ Id: this.billId, postPaymentFee: this.postPaymentFee }).then(response => {
        this.dialogPaymentVisible = false
        this.getdata()
      }).finally(() => {
        this.postPaymentFee = 0
      })
    },
    setPayment() {
      this.dialogPaymentVisible = true
    },
    getPaymentLog() {
      this.dialogFees = true
      _getPaymentLog(this.billId).then(response => {
        this.PaymentData = response
      })
    },
    setNotConfirmeds() {
      this.dialogNotConfirmed = true
    },
    setInputSupplementOrDeduction() {
      this.dialogInputSupplementOrDeduction = true
    },
    setClaims() {
      const billId = this.billId
      var data = this.getCurrentDataByStatus()
      const bill = data.find(i => i.Id == billId)
      if (!bill) {
        this.$message(`无法找到对应的账单信息,ID:${billId}`)
      } else {
        this.currentClaimBill = bill
      }
      this.dialogClaimVisible = true
    },
    getCurrentDataByStatus() {
      if (this.status == '0') return this.s1Data
      else if (this.status == '1') return this.s2Data
      else if (this.status == '2') return this.s3Data
      else if (this.status == '3') return this.s4Data
      else if (this.status == '4') return this.s5Data
      else throw (new Error(`该状态(${status})没有对应数据`))
    },
    getdata() {
      var that = this
      const billingCycle = !this.formReconcile.billingCycle ? 0 : this.formReconcile.billingCycle
      const data = { status: this.status, customerId: this.formReconcile.customerId, billingCycle,IsInterceptCustomers:this.formReconcile.IsInterceptCustomers}
      this.searchLoading = true
      _getPostData(data).then(response => {
        for (var i = 0; i < response.length; i++) {
          for (var j = 0; j < that.Customers.length; j++) {
            if (that.Customers[j].Id == response[i].CustomerId) { 
              response[i].CustomerName = that.Customers[j].CompanyName
              response[i].IsInterceptCustomers = that.Customers[j].IsInterceptCustomers
             }
          }
        }
        if (this.status == '0') { this.s1Data = response } else if (this.status == '1') { this.s2Data = response } else if (this.status == '2') { this.s3Data = response } else if (this.status == '3') { this.s4Data = response } else if (this.status == '4') {
          this.s5Data = response
        }
        this.searchLoading = false
      }).catch(() => {
        this.searchLoading = false
      })
      _getQtys().then(response => {
        for (var i = 0; i < response.length; i++) {
          var data = response[i]
          if (data.Key == 0) {
            this.s1 = data.Value
          }
          if (data.Key == 1) {
            this.s2 = data.Value
          }
          if (data.Key == 2) {
            this.s3 = data.Value
          }
          if (data.Key == 3) {
            this.s4 = data.Value
          } else if (data.Key == 4) {
            this.s5 = data.Value
          }
        }
      })
    },
    postStart() {
      this.createDto.StartTime = this.createDto.DelvieryDate[0]
      this.createDto.EndTime = this.createDto.DelvieryDate[1]
      var loading = Loading.service()
      var method = _addDeliveryBill
      if (this.status == 3) { method = _addDeliveryBillAsFile }

      method(this.createDto).then(response => {
        this.createDto.StartTime = ''
        this.createDto.EndTime = ''
        this.createDto.ServiceBillUrl = ''
        this.createDto.Name = ''
        this.createDto.Curreny = ''
        this.createDto.CustomerId = 0
        this.createDto.DelvieryDate = []
        this.dialogStartVisible = false
        this.getdata()
        loading.close()
      }).error(ex => {
        loading.close()
      })
    },
    postConfirmed() {
      var loading = Loading.service()
      _updateConfirmed({ billId: this.billId, url: this.tempUrl }).then(
        response => {
          this.getdata()
          this.dialogNotConfirmed = false
          loading.close()
        }).error(ex => {
        loading.close()
      })
      this.tempUrl = ''
    },
    postSupplementOrDeduction() {
      _inputSupplementOrDeduction({ billId: this.billId, url: this.tempUrl, type: this.feeType }).then(
        response => {
          this.getdata()
          this.dialogInputSupplementOrDeduction = false
        })
      this.tempUrl = ''
    },
    setRejectBill(billId) {
      this.billId = billId
      this.dialogRejectVisible = true
    },
    setPassBill(billId) {
      this.billId = billId
      this.dialogConfirmVisible = true
    },
    postPass() {
      _Pass({ billId: this.billId })
        .then(response => {
          this.getdata()
          this.dialogConfirmVisible = false
          this.billId = 0
        })
    },
    postReject() {
      _Rereject({ billId: this.billId })
        .then(response => {
          this.getdata()
          this.dialogRejectVisible = false
          this.billId = 0
        })
    },
    changeCreateBillUrl(r) {
      this.createDto.ServiceBillUrl = r.Data.url
    },
    changeTempUrl(r) {
      this.tempUrl = r.Data.url
    },
    billStateTagType(val) {
      return billStateTagType.get(val)
    },
    // 重新生成
    rerunBill(row) {
      // console.log(row, '重新生成')
      const _this = this
      // 参数
      const data = {
        Id: row.Id,
        Name: row.Name,
        StartTime: row.StartTime,
        EndTime: row.EndTime,
        CustomerId: row.CustomerId
      }
      this.$confirm('是否确定重新生成该帐单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        _ReProcessDeliveryBill(data).then(response => {
          _this.$message({
            type: 'success',
            message: '重新生成成功!'
          })
        }).catch(() => {
          _this.$message({
            type: 'error',
            message: '系统异常!'
          })
        })
      }).catch(() => {
        console.log('已取消')
      })
    },
    handleSelectionChange(val) {
      this.billIdList = val.map(item => ({ billId: item.Id, name: item.Name, billingCycle: item.BillingCycle }))
      console.log(this.billIdList, ':this.billIdList')
    },
    // 对账查询
    searchReconcile() {
      this.getdata()
    },
    // 批量下载
    batchReconcile() {
      // 循环导出数据
      try {
        for (const item of this.billIdList) {
          _getOutCustomerBatch(item.billId, 1, item.billingCycle, item.name)
        }
      } catch (error) {
        this.$message.error('批量下载失败' + error)
      }
    }
  }
}

</script>

<style>
    .el-pagination
    {
         margin-top:10px;
    }
    .el-dialog .el-form .el-input, .el-dialog .el-form .el-select{
        width:300px;
    }
</style>
