<template>
  <div class="pageBox">
    <div class="searchBox">
      <div class="row">
        <span class="span">ID：</span>
        <div class="right"><el-input v-model="filter.id" class="wid100" clearable></el-input></div>
      </div>
      <div class="row">
        <span class="span">供应商名称：</span>
        <div class="right">
          <el-select v-model="filter.purchase_supplier_id" placeholder="请选择" clearable filterable>
            <el-option v-for="it in suppliersList" :key="it.id" :label="it.supplier_name" :value="it.id" />
          </el-select>
        </div>
      </div>
      <div class="row">
        <span class="span">提交时间：</span>
        <div class="right">
          <el-date-picker
            v-model="submitTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%;box-sizing: border-box;">
          </el-date-picker>
        </div>
      </div>
      <div class="row">
        <span class="span">审批类型：</span>
        <div class="right">
          <el-select v-model="filter.approval_type" placeholder="请选择" clearable class="wid100">
            <el-option label="采购订单审批" :value="1" />
            <el-option label="预付款打款审批" :value="2" />
            <el-option label="尾款打款审批" :value="3" />
            <el-option label="已结束" :value="4" />
          </el-select>
        </div>
      </div>
      <div class="row row1">
        <el-button type="primary" @click="handleSearch"><el-icon><Search /></el-icon>&nbsp;筛选</el-button>
      </div>
    </div>

    <el-card shadow="never">
      <div class="opaBox">
        <el-button type="primary" @click="handleAdd"><el-icon><Plus /></el-icon>&nbsp;新增</el-button>
      </div>
      <el-table :data="goodsList" style="width: 100%" border v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="type" label="采购类型" align="center">
          <template #default="scope">
            <span>{{ approvalType[scope.row.approval_type] }}</span>
            
            <div v-if="scope.row.approval_type == 1" :class="'status' + scope.row.order_approval_status">{{ approvalStatus[scope.row.order_approval_status] }}</div>
            <div v-else-if="scope.row.approval_type == 2" :class="'status' + scope.row.prepayment_approval_status">{{ approvalStatus[scope.row.prepayment_approval_status] }}</div>
            <div v-else-if="scope.row.approval_type == 3" :class="'status' + scope.row.final_payment_approval_status">{{ approvalStatus[scope.row.final_payment_approval_status] }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="purchase_supplier.supplier_name" label="采购供应商" />
        <el-table-column label="申请采购商品信息">
          <template #default="scope">
            <div v-if="scope.row.products">
              <div v-for="it in scope.row.products" :key="it.id">{{it.goods && it.goods.title}}（{{ it.unit }}）</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="总预计订单金额/总预防款/总尾款" align="center">
          <template #default="scope">
            <div>{{ scope.row.total_amount }}</div>
            <div>{{ scope.row.prepayment_amount }}</div>
            <div>{{ scope.row.final_payment_amount }}</div>
          </template>
        </el-table-column>
        <el-table-column label="总实际订单金额/总实际已支付金额/总实际未支付金额" align="center">
          <template #default="scope">
            <div>{{ scope.row.has_paid_amount }}</div>
            <div>{{ scope.row.has_paid_prepayment_amount }}</div>
            <div>{{ scope.row.has_paid_final_payment_amount }}</div>
          </template>
        </el-table-column>
        <el-table-column label="提交人/提交时间" align="center">
          <template #default="scope">
            <div>{{ scope.row.admin_user && scope.row.admin_user.username || '-' }}</div>
            <span>{{ scope.row.created_at }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="260">
          <template #default="scope">
            <div class="elbtn">
              <el-button type="primary" v-if="scope.row.approval_type != 4" text @click="resubmit(scope.row.id)"><el-icon><RefreshLeft /></el-icon>重新提审</el-button>

              <el-button type="primary" text @click="toPrepayment(scope.row.id)" v-if="(scope.row.approval_type == 1 && scope.row.order_approval_status == 2) || (scope.row.approval_type == 2 && scope.row.prepayment_approval_status == 3)"><el-icon><Position /></el-icon>发起预付款审批</el-button>
              
              <el-button type="primary" text @click="toPayment(scope.row.current_instance_id)"
                v-if="(scope.row.approval_type == 2 && scope.row.prepayment_approval_status == 2) || (scope.row.approval_type == 3 && scope.row.final_payment_approval_status == 2)">
                <el-icon><Upload /></el-icon>上传支付凭证
              </el-button>

              <el-button type="primary" text @click="toBalancePayment(scope.row.id)"
                v-if="(scope.row.approval_type == 2 && scope.row.prepayment_approval_status == 4) || (scope.row.approval_type == 3 && scope.row.final_payment_approval_status == 3)  || (scope.row.approval_type == 3 && scope.row.final_payment_approval_status == 4 && scope.row.total_amount * 1 > scope.row.has_paid_amount * 1)">
                <el-icon><Position /></el-icon>尾款打款审批
              </el-button>

              <el-button type="primary" text @click="toInvoice(scope.row.id)" v-if="scope.row.approval_type != 4"><el-icon><Upload /></el-icon>上传发票</el-button>
              <el-button type="danger" text @click="endApproval(scope.row.id)" v-if="scope.row.final_payment_approval_status == 4 && scope.row.approval_type != 4"><el-icon><SwitchButton /></el-icon>结束审批</el-button>
              <el-button type="primary" text @click="handleView(scope.row.id)"><el-icon><ZoomIn /></el-icon>查看详情</el-button>
              <el-button type="info" text @click="openLogs(scope.row.id)"><el-icon><Clock /></el-icon>审批记录</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="page-pagination">
        <el-pagination
          :current-page="page"
          background
          layout="prev, pager, next, sizes, total"
          :total="total"
          :page-sizes="[10, 50, 100]"
          :page-size="pageSize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"></el-pagination>
      </div>
    </el-card>

    <!-- 预览图片 -->
    <el-dialog v-model="picVisible" center width="800px">
      <img :src="dialogImageUrl" style="max-width: 700px; margin: 0 auto;display: block;" />
    </el-dialog>

    <el-dialog v-model="showAdd" width="500px" title="新增审批">
      <el-form label-position="right" label-width="10px">
        <el-form-item label="">
          <el-radio-group v-model="add_type">
            <el-radio :label="1">采购订单审批</el-radio>
            <el-radio :label="2">预付款打款审批</el-radio>
            <el-radio :label="3">尾款打款审批</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAdd = false">取消</el-button>
          <el-button type="primary" @click="curId = 0, showOrderApproval = true, showAdd = false">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 订单审批 -->
    <order-approval :show="showOrderApproval" :type="elType" :id="curId" @refresh="handleSearch" @close="showOrderApproval = false"></order-approval>

    <!-- 预付款审批 -->
    <order-prepayment :show="showPrepayment" :id="curId" @refresh="fetchData" @close="showPrepayment = false"></order-prepayment>

    <!-- 上传支付凭证 -->
    <upload-payment :show="showPayment" :id="curId" @refresh="fetchData" @close="showPayment = false"></upload-payment>

    <!-- 尾款审批 -->
    <balance-payment :show="showBalance" :id="curId" @refresh="fetchData" @close="showBalance = false"></balance-payment>

    <!-- 修改信息 -->
    <update-approval :show="showEditApproval" :id="curId" @refresh="fetchData" @close="showEditApproval = false"></update-approval>

    <!-- 修改信息 -->
    <approval-logs :show="showApprovalLogs" :id="curId" @close="showApprovalLogs = false"></approval-logs>

    <!-- 上传发票 -->
    <upload-invoice :show="showInvoice" :id="curId" @close="showInvoice = false"></upload-invoice>

  </div>
</template>

<script>
import { onMounted, reactive, toRefs, ref, nextTick } from "vue"
import { get, post } from "@/api/request"
import { Search, Plus, Edit, ZoomIn, Delete, RefreshLeft, SwitchButton, Position, Upload, Clock } from '@element-plus/icons'
import { ElMessage, ElMessageBox } from 'element-plus'
import orderApproval from '@/components/approval/order.vue'
import orderPrepayment from '@/components/approval/prepayment.vue'
import uploadPayment from '@/components/approval/uploadpayment.vue'
import balancePayment from '@/components/approval/balancepayment.vue'
import updateApproval from '@/components/approval/update.vue'
import approvalLogs from '@/components/approval/logs.vue'
import uploadInvoice from '@/components/approval/uploadinvoice.vue'

export default {
  components: {
    Search, Plus, Edit, ZoomIn, Delete, RefreshLeft, SwitchButton, Position, Upload, Clock,
    uploadPayment, balancePayment, updateApproval, orderApproval, orderPrepayment, approvalLogs, uploadInvoice
  },
  setup() {
    const data = reactive({
      add_type: 1,
      showAdd: false,
      showEditApproval: false,
      showOrderApproval: false,
      showApprovalLogs: false,
      showInvoice: false,
      showPayment: false,
      showBalance: false,
      showPrepayment: false,
      filter: {},
      submitTime: [],
      goodsList: [],
      page: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      picVisible: false,
      dialogImageUrl: '',
      approvalType: {
        '1': '采购订单审批',
        '2': '预付款打款审批',
        '3': '尾款打款审批',
        '4': '已结束'
      },
      approvalStatus: {
        '0': '草稿',
        '1': '进行中',
        '2': '已完成',
        '3': '已驳回',
        '4': '上传凭证'
      },
      warehouseList: [],
      suppliersList: [],
      allGoodsList: [],
      curId: 0,
      elType: ''
    })

    function handleSearch() {
      data.page = 1
      fetchData()
    }

    const fetchData = () => {
      data.loading = true
      let params = {
        page: data.page,
        pageSize: data.pageSize,
        ...data.filter,
        start_date: data.submitTime ? data.submitTime[0] : '',
        end_date: data.submitTime ? data.submitTime[1] : ''
      }
      get(`/api/purchaseOrder`, params).then((res) => {
        data.goodsList = res.data
        data.total = res.meta.total
        data.loading = false
      }).catch(() => {
        data.loading = false
      })
    }

    function handleCurrentChange(e) {
      data.page = e
      fetchData()
    }

    function handleSizeChange(e) {
      data.page = 1
      data.pageSize = e
      fetchData()
    }

    function getWarehouseList() {
      get(`/api/all/warehouses`).then((res) => {
        data.warehouseList = res.data
      })
    }

    function getSuppliersList() {
      get(`/api/purchaseSupplier`, {pageSize: 1000}).then((res) => {
        data.suppliersList = res.data
      })
    }

    function getAllGoodsList() {
      get(`/api/all/goods`).then((res) => {
        data.allGoodsList = res.data
      })
    }

    function resubmit(id) {
      data.curId = id
      data.showEditApproval = true
    }

    function toPrepayment(id) {
      data.curId = id
      data.showPrepayment = true
    }

    function toPayment(id) {
      data.curId = id
      data.showPayment = true
    }

    function toBalancePayment(id) {
      data.curId = id
      data.showBalance = true
    }

    function openLogs(id) {
      data.curId = id
      data.showApprovalLogs = true
    }

    function toInvoice(id) {
      data.curId = id
      data.showInvoice = true
    }

    function endApproval(id) {
      ElMessageBox.confirm('确定要结束当前审批流程吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        post(`/api/purchaseOrder/endProcess`, {purchase_order_id: id}).then(() => {
          fetchData()
          ElMessage({ type: 'success', message: '操作成功' })
        })
      })
    }

    function handleAdd() {
      data.elType = ''
      data.curId = 0
      data.showOrderApproval = true
    }

    function handleView(id) {
      data.elType = 'view'
      data.curId = id
      data.showOrderApproval = true
    }

    onMounted(() => {
      fetchData()
      getWarehouseList()
      getSuppliersList()
      getAllGoodsList()
    })

    return {
      ...toRefs(data),
      handleAdd,
      handleSearch,
      handleCurrentChange,
      handleSizeChange,
      fetchData,
      getWarehouseList,
      getSuppliersList,
      getAllGoodsList,
      resubmit,
      endApproval,
      toPrepayment,
      toPayment,
      toBalancePayment,
      openLogs,
      toInvoice,
      handleView
    }
  }
}
</script>

<style lang="scss" scoped>
  .searchBox{
    display: flex;
    flex-wrap: wrap;
    background-color: #fff;
    padding: 15px 15px 0 0;
    border-radius: 4px;
    margin-bottom: 15px;
    .row{
      display: flex;
      align-items: center;
      width: 20%;
      box-sizing: border-box;
      margin-bottom: 15px;
      .span{
        display: block;
        width: 100px;
        font-size: 14px;
        text-align: right;
        box-sizing: border-box;
      }
      .right{
        width: calc(100% - 100px);
      }
      .wid100{
        width: 100%;
      }
      &.row1{
        margin-left: 15px;
        width: auto;
      }
    }
  }
  .opaBox{
    margin-bottom: 15px;
  }
  .imgBox{
    display: flex;
    flex-wrap: wrap;
    .el-image{
      width: 60px;
      height: 60px;
      border-radius: 4px;
      margin-right: 10px;
    }
  }
  .skuBox{
    border: 1px solid #e5e5e5;
    border-radius: 5px;
    padding: 15px 0;
    margin-bottom: 15px;
    background-color: #f3f3f3;
    .tit{
      padding-left: 40px;
      font-weight: 600;
      font-size: 15px;
      margin-bottom: 15px;
    }
  }
  ::v-deep .elbtn .el-button.is-text{
    padding: 8px 0px;
  }
  .status1{
    color: #f90;
  }
  .status2{
    color: #67C23A;
  }
  .status3{
    color: #909399;
  }
  .status4{
    color: #F56C6C;
  }
</style>
