<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"
        label-width="100px"
        class="card"
      >
        <el-row :gutter="10">
          <el-col :span="4"> <el-form-item :label="$t('付款单号')">
            <el-input
              clearable
              style="max-width: 188px"
              v-model="queryParams.paymentNo"
              :placeholder="$t('请输入付款单号')"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item></el-col>
          <el-col :span="4"><el-form-item :label="$t('供应商')">
            <el-select
              clearable
              v-model="queryParams.supplierId"
              :placeholder="$t('请选择供应商')"
            >
              <el-option
                v-for="supplier in allSupplier"
                :key="supplier.id"
                :label="supplier.companyZh"
                :value="supplier.id"
              ></el-option>
            </el-select>
          </el-form-item></el-col>
          <el-col :span="4"><el-form-item :label="$t('业务员')">
            <!--            <el-select v-model="form.salesmanId" :placeholder="$t('请选择业务员')">
                          <el-option
                            v-for="item in creatorData"
                            :key="item.id"
                            :label="item.nickname"
                            :value="item.id"
                          />
                        </el-select> -->
            <el-select v-model="queryParams.salesmanName" filterable :placeholder="$t('请选择业务员')"
                       clearable
                    >
              <el-option
                v-for="item in creatorData"
                :key="item.id"
                :label="item.nickname"
                :value="item.nickname"
              />
            </el-select>
          </el-form-item> </el-col>
          <el-col :span="6"><el-form-item :label="$t('创建时间')">
            <el-date-picker
              v-model="queryParams.beginCreateTime"
              type="datetimerange"
              value-format="yyyy-MM-dd"
              range-separator="到"
              :start-placeholder="$t('请选择日期')"
              :end-placeholder="$t('请选择日期')">
            </el-date-picker>
          </el-form-item></el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="4">
            <el-form-item :label="$t('状态')">
              <dict-selector   clearable :type="DICT_TYPE.ECW_PAYMENT_STATE" v-model="queryParams.state"/>
            </el-form-item>
          </el-col>
          <el-col :span="4"><el-form-item :label="$t('发票状态')">
            <el-select
              clearable
              v-model="queryParams.invoiceStatus"
              :placeholder="$t('请选择是否开票')"
            >
              <el-option :label="$t('未开票')" value="0"/>
              <el-option :label="$t('已开票')" value="1"/>
            </el-select>
          </el-form-item></el-col>
          <el-col :span="6"><el-form-item>
            <el-button type="primary" @click="handleQuery">{{ $t('查找') }}</el-button>
            <el-button
              style="margin-left: 10px"
              type="success"
              v-hasPermi="['ecw:paymentVoucher:create']"
              @click="handleAdd(0)"
            >{{ $t('新增请款单') }}</el-button
            >
          </el-form-item></el-col>
        </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="paymentNo">
        <template slot-scope="scope">
          <span style="color: #1890ff;" @click="paymentDetail(scope.row)">{{ scope.row.paymentNo }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('供应商')" align="center" prop="supplierName"/>
      <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="latestPayAt">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.latestPayAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('发票')" align="center" prop="invoiceStatus">
        <template slot-scope="scope">
          <span>{{ scope.row.invoiceStatus === 0 ? $t('未开票') : $t('已开票') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('状态')" align="center">
        <template slot-scope="scope">
          <dict-tag
            :type="DICT_TYPE.ECW_PAYMENT_STATE"
            :value="scope.row.state"
          />
          <span v-if="[2,4,6].includes(scope.row.state) && scope.row.comment" :title="scope.row.comment"><i class="el-icon-question"></i></span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('操作')"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template v-slot="{row}">
          <el-button v-if="[0,2].includes(row.state)" size="mini" @click="handleAdd(row.id)"
                     v-hasPermi="['ecw:paymentVoucher:edit']" type="text">{{ $t('编辑') }}
          </el-button>
          <!--          <el-button v-if="[1,3].includes(row.state)" size="mini" v-hasPermi="['ecw:paymentVoucher:process']" type="text" @click="examineClick(scope.row.id)">{{ $t('审核') }}</el-button>-->
          <el-button size="mini"  type="text" v-show="[1].includes(row.state)" v-hasPermi="['ecw:paymentVoucher:Unapprove']"  @click="bridgeFn(1, $t('取消审核'),row)">
            {{ $t('取消审核') }}
          </el-button>
          <el-button size="mini" type="text" v-show="[7,3,1,5].includes(row.state)"  v-hasPermi="['ecw:paymentVoucher:details']" @click="$router.push({path:'/bpm/process-instance/detail',query:{id:row.bmpId}})" >{{ $t('审核详情') }}</el-button>
          <el-button size="mini" type="text"  v-if="[3].includes(row.state)" v-hasPermi="['ecw:paymentVoucher:Cancel-De-approval']" @click="bridgeFn(2, $t('取消付款单反审核'),row)" >{{ $t('取消反审核') }}</el-button>
          <el-button size="mini"  type="text" v-if="[5].includes(row.state)" v-hasPermi="['ecw:paymentVoucher:Cancel-Write-off']" @click="bridgeFn(3, $t('取消付款单核销'),row)"  >{{ $t('取消核销') }}</el-button>

          <el-button v-if="[4].includes(row.state)" size="mini" type="text" v-hasPermi="['ecw:paymentVoucher:De-approval']"
                     @click="bridgeFn(4, $t('反审核'),row)">{{ $t('反审核') }}
          </el-button>
          <el-button v-if="[4].includes(row.state)" size="mini" type="text" v-hasPermi="['ecw:paymentVoucher:writeOff']"
                     @click="bridgeFn(5, $t('核销'),row)">{{ $t('核销') }}
          </el-button>

          <el-button v-if="[6].includes(row.state)" size="mini" type="text"
                     v-hasPermi="['ecw:paymentVoucher:cancelWriteOff']" @click="bridgeFn(6, $t('反核销'),row)">
            {{ $t('反核销') }}
          </el-button>
          <el-button  v-if="[7].includes(row.state)" v-hasPermi="['ecw:paymentVoucher:Cancel-Cancelling-Write-off']" size="mini" type="text" @click="bridgeFn(7, $t('取消付款单反核销'),row)" > {{ $t('取消反核销') }}</el-button>
          <!-- <el-button v-if="scope.row.state == 3" size="mini" type="text">{{ $t('开票') }}</el-button> -->

          <el-button v-if="[6,4].includes(row.state)" size="mini" type="text" @click="toprint(row.id)"
                     v-hasPermi="['ecw:paymentVoucher:print']">{{ $t('打印') }}
          </el-button>
          <el-button v-if="[0,2].includes(row.state)" size="mini" type="text" v-hasPermi="['ecw:paymentVoucher:delete']"
                     @click="deleteClick(row)">{{ $t('删除') }}
          </el-button>
          <!-- <el-button size="mini" type="text" @click="open = true">{{ $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="header"
        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"
        >{{ $t('国内账单') }}
        </el-button
        >
        <el-button
          plain
          type="primary"
          style="width: 130px; margin: 0"
          @click="submitForm"
        >Debite note
        </el-button
        >
      </div>
    </el-dialog>
    <!--对话框 审核 -->
    <el-dialog width="30%" @close="cancelReason = ''" :title="examineTitle" :visible.sync="examineShow">
      <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="examineShow = false;">{{ $t('取消') }}</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import {userList, listSimpleUsers} from "@/api/system/user";
import {DICT_TYPE} from "@/utils/dict";
import CustomerSelector from "@/components/CustomerSelector";
import {getSupplierPage} from "@/api/ecw/supplier";
import {
  getPaymentList,
  deletePayment,
  paymentVerification,
  paymentVerificationCancel,
  paymentVerifyCancel,
  cancelFinancePaymentApproval,
  cancelFinancePaymentApprovalNo,
  cancelFinancePaymentWriteOff,
  cancelFinancePaymentWriteOffNo, paymentCancelFinancePaymentWriteOffNo
} from "@/api/ecw/financial"

export default {
  name: "EcwFinancialPaymentvoucher",
  components: {
    CustomerSelector,
  },
  data() {
    return {
      examineShow: false,
      examineTitle: '',
      examineIndex: 0,
      examineData: {},
      cancelReason: '',
      open: false,
      showSearch: true,
      loadings: false,
      form: {},
      creatorData: [],
      allSupplier: [],
      list: [],
      total: 0,
      dateType: [],
      loading: "",
      // params: {
      //   page: 1,
      //   rows: 20,
      // },
      // 查询参数
      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,
      },
    };
  },
  activated() {
    this.handleQuery()
  },
  created() {
    let that = this;
    listSimpleUsers().then((res) => (that.creatorData = res.data));
    // userList("salesman").then((res) => (that.creatorData = res.data));
    getSupplierPage({pageNo: "1", pageSize: "10000"}).then((res) => {
      const {data} = res;
      this.allSupplier = data.list;
    });
    this.getList()
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 处理查询参数
      let params = {...this.queryParams};
      this.addBeginAndEndTime(params, this.queryParams.beginCreateTime, "createTime");
      // 执行查询
      getPaymentList(params).then((response) => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    paymentDetail(row) {
      const id = row.id;
      return this.$router.push("paymentDetail?id=" + id);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    stateMap(state) {
      switch (state) {
        case 1:
          return this.$t('待审核')
        case 2:
          return this.$t('已审核待核销')
        case 3:
          return this.$t('审批驳回')
        case 4:
          return this.$t('已核销')
      }
    },
    /** 新增按钮操作 */
    handleAdd(id) {
      return this.$router.push("creatPayment?id=" + id);
    },
    examineClick(id) {
      return this.$router.push("paymentExamine?id=" + id);
    },
    deleteClick(row) {
      const id = row.id;
      this.$modal.confirm(this.$t('是否确认删除该付款单') + '?').then(function () {
        return deletePayment(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(this.$t('删除成功'));
      }).catch(() => {
      });
    },
    verificationClick(row) {
      const id = row.id;
      this.$modal.confirm(this.$t('您确认要核销吗') + '?').then(function () {
        return paymentVerification(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(this.$t('核销成功'));
      }).catch(() => {
      });
    },
    verificationCancelClick(row) {
      const id = row.id;
      this.$modal.confirm(this.$t('您确认要反核销吗') + '?').then(function () {
        return paymentVerificationCancel(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(this.$t('反核销成功'));
      }).catch(() => {
      });
    },
    verifyCancelClick(row) {
      const id = row.id;
      this.$modal.confirm(this.$t('您确认要反审核吗') + '?').then(function () {
        return paymentVerifyCancel(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(this.$t('反审核成功'));
      }).catch(() => {
      });
    },
    toprint(id) {
      return this.$router.push("printPaymentVoucher?id=" + id);
    },
    submitForm() {
      this.open = false;
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
    },
    bridgeFn(index, title, row) {
      this.examineIndex = index;
      this.examineTitle = title;
      this.examineData = row;
      this.examineShow = true;
    },
    cancelWriteOffClick() {
      if(!this.cancelReason){
        return this.$message.warning(this.$t('请输入申请理由！'))
      }
      let resolve = (val = this.$t('操作成功吗！')) => {
        this.getList();
        this.$message.success(val);
        this.examineShow = false;
      }
      let reject = () => {
        this.examineShow = false;
      }
      let {id: paymentId,paymentNo} = this.examineData
      let p = {paymentId, remark: this.cancelReason, paymentNo, reason:this.cancelReason }
      switch (this.examineIndex) {
        case 1:
          // 取消审核
          cancelFinancePaymentApproval(p).then(()=>resolve(this.$t('取消付款单审核成功！')),reject)
          break
        // 取消付款单反审核
        case 2:
          cancelFinancePaymentApprovalNo(p).then(()=>resolve(this.$t('取消付款单反审核成功！')),reject)
          break;
        case 3:
          //取消付款单核销
          cancelFinancePaymentWriteOffNo(p).then(()=>resolve(this.$t('取消付款单核销成功！')),reject)
          break
        case 4:
      // 反审核
          paymentVerifyCancel(p).then(()=>resolve(this.$t('提交付款单反审核成功，请耐心等待审核结果!')),reject)
          break;
        case 5:
      // 核销
          paymentVerification(p).then(()=>resolve(this.$t('提交付款单核销成功，请耐心等待审核结果！')),reject);
          break;
        case 6:
            // 反核销
            paymentVerificationCancel(p).then(()=>resolve(this.$t('提交付款单反核销成功，请耐心等待审核结果!')),reject)
          break;
        case 7:
          //  取消反核销
          paymentCancelFinancePaymentWriteOffNo(p).then(()=>resolve(this.$t('取消付款单反核销成功！')),reject)
          break;


      }
    }
  },
};
</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;
}

.card-title {
  font-size: 18px;
  font-weight: bold;
}
</style>
