<template>
  <div class="app-container">
    <div slot="header" class="card-title">{{ $t('收款单') }}</div>
    <!-- 搜索工作栏 -->
    <el-card v-show="showSearch" class="card">
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        label-width="100px"
        class="card"
      >
        <el-row :span="24">
          <el-form-item :label="$t('收款单号')">
            <el-input
              style="max-width: 188px"
              v-model="queryParams.receiptNo"
              :placeholder="$t('请输入收款单号')"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item :label="$t('客户名称')">
            <customer-selector
              v-model="queryParams.customerId"
              @change="changeCustomerId"
              clearable
            />
          </el-form-item>
          <el-form-item :label="$t('状态')">
            <dict-selector
              :type="DICT_TYPE.ECW_RECEIPT_STATE"
              v-model="queryParams.state"
              clearable
            />
          </el-form-item>
          <el-form-item :label="$t('业务员')">
            <el-select
              v-model="queryParams.salesmanId"
              :placeholder="$t('请选择业务员')"
              clearable
            >
              <el-option
                v-for="item in creatorData"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row :span="24">
          <el-col style="width: 592px">
            <el-form-item :label="$t('创建时间')">
              <el-date-picker
                v-model="dateFilter"
                type="datetimerange"
                range-separator="-"
                value-format="yyyy-MM-dd HH:mm:ss"
                :start-placeholder="$t('请选择日期')"
                :end-placeholder="$t('请选择日期')"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">{{ $t('查找') }}</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </el-card>
    <el-table v-loading="loadings" :data="list" border class="card">
      <el-table-column :label="$t('序号')" align="center" prop="id" type="index">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('收款单号')" align="center" prop="receiptNo" />
        <!-- <template slot-scope="scope"> -->
          <!-- <span style="color: #1890ff;" @click="verificationCancelClick(scope.row)">{{scope.row.receiptNo}}</span> -->
        <!-- </template> -->
      <!-- </el-table-column> -->
      <el-table-column :label="$t('客户名称')" align="center" prop="customerName" />
      <el-table-column :label="$t('创建日期')" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('实收日期')" align="center" prop="payedAt">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.payedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('业务员')" align="center" prop="salesmanName" />
      <el-table-column :label="$t('状态')" align="center">
        <template slot-scope="scope">
          <dict-tag
            :type="DICT_TYPE.ECW_RECEIPT_STATE"
            :value="scope.row.state"
          />
          <span v-if="scope.row.remark&&(scope.row.state==1 || scope.row.state ==3 || scope.row.state==8)" :title="scope.row.remark"><i class="el-icon-question"></i></span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('是否开票')" align="center">
        <template slot-scope="scope">
          {{ scope.row.openInvoice === 0 ? $t('否') : $t('是') }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('操作')"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            v-hasPermi="['ecw:voucher:see']"
            @click="verificationCancelClick(scope.row)"
            >{{ $t('查看')}}</el-button>
          <el-button
            v-if="scope.row.state === 0"
            size="mini"
            type="text"
            v-hasPermi="['ecw:voucher:edit']"
            @click="handleAdd(scope.row.id)"
            >{{ $t('编辑') }}</el-button
          >
          <!-- <el-button
            v-if="scope.row.state == "
            size="mini"
            type="text"
            @click="verificationClick(scope.row)"
            >{{ $t('核销') }}</el-button
          > -->
          <el-button
            v-if="scope.row.state == 4 || scope.row.state == 5 || scope.row.state == 6"
            size="mini"
            type="text"
            v-hasPermi="['ecw:voucher:cancelWriteOff']"
            @click="writeOffShow(2,scope.$index)"
            >{{ $t('反核销') }}</el-button
          >
          <el-button
            v-if="scope.row.state == 1"
            size="mini"
            type="text"
            v-hasPermi="['ecw:voucher:deApproval']"
            @click="writeOffShow(1,scope.$index)"
            >{{ $t('反审核') }}</el-button
          >
         <el-button
            v-if="scope.row.state == 7"
            size="mini"
            type="text"
            v-hasPermi="['ecw:vocher:cancelAppoval']"
            @click="cancelClick(scope.$index,1)"
            >{{ $t('取消审核') }}</el-button
          >
          <el-button
            v-if="scope.row.state == 11"
            size="mini"
            type="text"
            v-hasPermi="['ecw:vocher:cancelWriteOfflNo']"
            @click="cancelClick(scope.$index,3)"
            >{{ $t('取消反核销审核') }}</el-button
          >
          <el-button
            v-if="scope.row.state == 10"
            size="mini"
            type="text"
            v-hasPermi="['ecw:vocher:cancelWriteOffAll']"
            @click="cancelClick(scope.$index,4)"
            >{{ $t('取消全部核销审核') }}</el-button
          >
          <el-button
            v-if="scope.row.state == 9"
            size="mini"
            type="text"
            v-hasPermi="['ecw:vocher:cancelAppovalNo']"
            @click="cancelClick(scope.$index,2)"
            >{{ $t('取消反审核') }}</el-button
          >
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.state == 9 || scope.row.state == 7 || scope.row.state == 11|| scope.row.state == 10"
            v-hasPermi="['ecw:voucher:cancelWriteOff']"
            @click="$router.push(`/bpm/process-instance/detail?id=`+scope.row.bmpId)"
            >{{ $t('审核详情') }}</el-button
          >
          <el-button
            v-if="scope.row.state == 5"
            size="mini"
            type="text"
            v-hasPermi="['ecw:voucher:ballot']"
            @click="openInvoice(scope.row.id)"
            >{{ $t('开票') }}</el-button
          >
          <el-button v-if="scope.row.state == 1 || scope.row.state == 2 || scope.row.state == 3"  v-hasPermi="['ecw:voucher:payment']" size="mini" type="text" @click="verificationCancelClick(scope.row)">{{ $t('收款') }}</el-button>
          <el-button v-if="scope.row.state == 0" size="mini" type="text"  v-hasPermi="['ecw:voucher:delete']" @click="deleteClick(scope.row)">{{ $t('删除') }}</el-button>
          <el-button
            v-if="scope.row.state != 0 && scope.row.state != 7 && scope.row.state != 11 && scope.row.state != 8 && scope.row.state != 9"
            size="mini"
            type="text"
            @click="toprint(scope.row.id)"
            v-hasPermi="['ecw:voucher:print']"
            >{{ $t('打印') }}</el-button
          >
          <el-button
            v-if="scope.row.state != 0 && scope.row.state != 7 && scope.row.state != 11 && scope.row.state != 8 && scope.row.state != 9"
            size="mini"
            type="text"
            v-hasPermi="['ecw:voucher:derive']"
            @click="exportReceipt(scope.row.id)"
            >{{ $t('导出账单') }}</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.rows"
      @pagination="getList"
    />
    <!-- 对话框(添加 / 修改) -->
    <el-dialog
      :title="$t('导出账单')"
      :visible.sync="open"
      width="500px"
      style="margin-top: 20vh !important"
      append-to-body
    >
      <!-- <div slot="title" class="card-title" style='border-bottom: 2px solid #f8f8f8;'>
            <span>{{ $t('导出账单') }}</span>
            <i class="el-icon-close" @click="cancel"></i>
          </div> -->
      <div class="dialog-footer">
        <el-button type="primary" style="width: 130px" @click="submitForm(1)" v-loading="downloading">{{ $t('国内账单') }}</el-button
        >
        <el-button
          plain
          v-loading="downloading"
          type="primary"
          style="width: 130px; margin: 0"
          @click="submitForm(2)"
          >Debite note</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
     :title="writeOffType==1?$t('收款单反审核'):$t('收款单反核销')"
      :visible.sync="dialogVisible"
      width="30%">
       <div class="cancel_content">
         <span>{{$t('申请理由')}}</span>
         <el-input type="textarea" :rows ="6" v-model="reason" :placeholder="$t('请输入理由')"></el-input>
       </div>
      <span slot="footer" class="dialog-footers">
        <el-button v-if="writeOffType==1" type="primary" @click="writeOffClick()">{{$t('提交反审核')}}</el-button>
        <el-button v-else type="primary" @click="writeOffClick()">{{$t('提交反核销')}}</el-button>
        <el-button @click="dialogVisible = false">{{$t('取消')}}</el-button>
      </span>
    </el-dialog>
    <el-dialog
     :title="cancelTitle"
      :visible.sync="cancelShow"
      width="30%">
       <div class="cancel_content">
         <span>{{$t('申请理由')}}</span>
         <el-input type="textarea" :rows ="6" v-model="cancelReason" :placeholder="$t('请输入取消理由')"></el-input>
       </div>
      <span slot="footer" class="dialog-footers">
        <el-button type="primary" @click="cancelWriteOffClick()">{{$t('提交')}}</el-button>
        <el-button @click="cancelShow = false">{{$t('取消')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listSimpleUsers } from "@/api/system/user";
import { DICT_TYPE } from "@/utils/dict";
import CustomerSelector from "@/components/CustomerSelector";
import {
  getReceiptList,
  // receiptVerification,
  // receiptVerificationCancel,
  receiptExportExcel,
  deleteReceipt,
  financeReceiptWriteOffNo,
  financeApproveNo,
  cancelFinanceReceiptApproval,
  cancelFinanceReceiptApprovalNo,
  cancelFinanceReceiptWriteOffNo,
  cancelFinanceReceiptWriteOff
} from "@/api/ecw/financial";

export default {
  name: "EcwFinancialVoucher",
  components: {
    CustomerSelector,
  },
  data() {
    return {
      exportId: "",
      open: false,
      showSearch: true,
      loadings: false,
      form: {},
      creatorData: [],
      list: [],
      total: 0,
      dateType: [],
      loading: "",
      params: {

      },
      // 查询参数
      queryParams: {
        page: 1,
        rows: 20,
        dateType: null,
        date: null,
        originId: null,
        destinationId: null,
        transportId: null,
        isCargoControl: null,
        orderExceptionStatus: null,
        orderExceptionType: null,
        orderNo: null,
        consignorId: null,
        marks: null,
        prodId: null,
        productRecord: null,
        followUpSalesmanId: null,
      },
      dateFilter:[],
      downloading: false, // 导出状态
      dialogVisible:false,
      reason:'',
      writeOffType:1,
      writeOffIndex:0,
      cancelShow:false,
      cancelTitle:'',
      cancelReason:'',
      cancelIndex:0,
      selectIndex:0
    };
  },
  activated(){
    this.getList();
  },
  created() {
    let that = this;
    listSimpleUsers().then((res) => (that.creatorData = res.data));
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      this.params = {}
      for(var key in this.queryParams){
          if(this.queryParams[key]){
            this.params[key] = this.queryParams[key]
          }
         }
      console.log(this.params)
      // 处理查询参数
      let params = { ...this.params };
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, "createTime");
      // 执行查询
      getReceiptList(params).then((response) => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    changeCustomerId(e){
      this.$set(this.queryParams,'customerId',e.id)
    },
    verificationClick(row) {
      const id = row.id;
      return this.$router.push("receiptDetail?id=" + id);
    //   this.$modal
    //     .confirm("您确认要核销吗？")
    //     .then(function () {
    //       return receiptVerification(id);
    //     })
    //     .then(() => {
    //       this.getList();
    //       this.$modal.msgSuccess("核销成功");
    //     })
    //     .catch(() => {});
    },
    verificationCancelClick(row) {
      const id = row.id;
      return this.$router.push("receiptDetail?id=" + id);
      // this.$modal
      //   .confirm("您确认要反核销吗？")
      //   .then(function () {
      //     return receiptVerificationCancel(id);
      //   })
      //   .then(() => {
      //     this.getList();
      //     this.$modal.msgSuccess("反核销成功");
      //   })
      //   .catch(() => {});
    },
    //显示取消审核弹窗
    cancelClick(index,type){
      this.selectIndex = index
      this.cancelIndex = type
      this.cancelReason = ''
      if(this.cancelIndex==1){
        this.cancelTitle = this.$t('取消审核')
      }else if(this.cancelIndex == 2){
         this.cancelTitle = this.$t('取消反审核')
      }else if(this.cancelIndex == 3){
         this.cancelTitle = this.$t('取消反核销审核')
      }else{
        this.cancelTitle = this.$t('取消全部核销审核')
      }
      this.cancelShow = true
    },
    //取消审核
    cancelWriteOffClick(){
      if(!this.cancelReason){
         this.$modal.msgError(this.$t('请输入申请理由'));
        return
      }
      var receiptId = this.list[this.selectIndex].id
      if(this.cancelIndex==1){
            cancelFinanceReceiptApproval({receiptId:receiptId,remark:this.cancelReason}).then(res=>{
              this.cancelShow = false
              this.getList();
              this.$message.success(this.$t("提交成功"));

            });
      }else if(this.cancelIndex ==2){
          cancelFinanceReceiptApprovalNo({receiptId:receiptId,remark:this.cancelReason}).then(res=>{
            this.cancelShow = false
            this.getList();
            this.$message.success(this.$t("提交成功"));

          });
      }else if(this.cancelIndex ==3){
          cancelFinanceReceiptWriteOffNo({receiptId:receiptId,remark:this.cancelReason}).then(res=>{
            this.cancelShow = false
            this.getList();
            this.$message.success(this.$t("提交成功"));

          });
      }else{
          cancelFinanceReceiptWriteOff({receiptId:receiptId,remark:this.cancelReason}).then(res=>{
            this.cancelShow = false
            this.getList();
            this.$message.success(this.$t("提交成功"));

          });
      }

    },
    writeOffClick(){
      if(!this.reason){
         this.$modal.msgError(this.$t('请输入申请理由'));
        return
      }
      const receiptIdData = this.list[this.writeOffIndex]
      if(this.writeOffType==1){
        // this.$alert()
        //   .confirm(this.$t('您确认要反审核吗')+'?')
        //   .then(()=>{
            financeApproveNo({receiptId:receiptIdData.id,receiptNo:receiptIdData.receiptNo,remark:this.reason}).then(res=>{
              this.getList();
              this.$message.success(this.$t("提交成功"));
              this.dialogVisible = false
              // this.$store.dispatch('tagsView/delCurrentView')
            });
          // })
          // .catch(() => {this.dialogVisible = false});
      }else{
        // this.$modal
        //   .confirm(this.$t('您确认要反核销吗')+'?')
        //   .then(()=>{
            financeReceiptWriteOffNo({receiptId:receiptIdData.id,receiptNo:receiptIdData.receiptNo,remark:this.reason}).then(res=>{
              this.getList();
              this.$message.success(this.$t("提交成功"));
              this.dialogVisible = false
              // this.$store.dispatch('tagsView/delCurrentView')
            });
          // })
          // .catch(() => {this.dialogVisible = false});
      }

    },
    deleteClick(row) {
      const id = row.id;
      this.$modal.confirm(this.$t('是否确认删除该收款单')+'?').then(function() {
        return deleteReceipt(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(this.$t('删除成功'));
      }).catch(() => {});
    },
    /** 搜索按钮操作 */
    handleQuery() {
      if(this.dateFilter&&this.dateFilter.length>0){
        this.queryParams.beginCreateTime = this.dateFilter[0]
        this.queryParams.endCreateTime = this.dateFilter[1]
      }else{
        this.queryParams.beginCreateTime = ''
        this.queryParams.endCreateTime = ''
      }

      this.queryParams.page = 1;
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd(id) {
      return this.$router.push("creatCollection?id=" + id);
    },
    toprint(id) {
      return this.$router.push("printVoucher?id=" + id);
    },
    openInvoice(id) {
      return this.$router.push("openInvoice?id=" + id);
    },
    exportReceipt(id) {
      this.open = true;
      this.exportId = id;
    },
    //显示反审核反核销弹窗
    writeOffShow(type,index){
      this.writeOffType = type
      this.writeOffIndex = index
      this.reason = ''
      this.dialogVisible = true
    },
    submitForm(type) {
      this.downloading = true
      receiptExportExcel({ id: this.exportId, billType: type }).then((response) => {
          this.$download.excel(response, `${type === 1 ? this.$t('国内账单') : "Debite_note"}.xls`);
          this.open = false;
        }
      ).finally(() => this.downloading = false)
    },
    /** 取消按钮 */
    //  cancel() {
    //    this.open = false;
    //  },
  },
};
</script>

 <style scoped>
.card {
  margin-top: 20px;
}
.dialog-footer {
  padding: 30px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  height: 160px;
}
.dialog-footers{
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.card-title {
  font-size: 18px;
  font-weight: bold;
}
  .cancel_content{
    display: flex;
    flex-direction: column;
  }
  .cancel_content span{
    font-size: 16px;
    font-weight:600;
    margin-bottom:10px
  }
</style>
