<template>
  <div class="mainContentBox">
    <avue-crud
        ref="crudRef"
        v-model:search="search"
        v-model="form"
        :data="data"
        :option="option"
        v-model:page="page"
        @row-save="createRow"
        @row-update="updateRow"
        @row-del="deleteRow"
        @search-change="searchChange"
        @search-reset="resetChange"
        @size-change="dataList"
        @current-change="dataList"
        @selection-change="selectionChange"
    >
      <template #menu-left="{ size }">
        <el-button
            type="primary"
            icon="el-icon-plus"
            :size="size"
            @click="openDialog(0,null)"
        >新增</el-button>

        <el-button
          :disabled="toDeleteIds.length < 1"
          type="danger"
          icon="el-icon-delete"
          :size="size"
          @click="multipleDelete"
          >删除</el-button
        >
      </template>
      <template #menu="{size,row,index}">
        <el-button
            type="info"
            link
            size="small"
            @click="openDialog(1,row)"
        ><i-ep-edit />查看</el-button>
        <el-button
            type="primary"
            link
            size="small"
            @click="openDialog(2,row)"
        ><i-ep-edit />{{row.state === '0' ? '编辑' : '流程'}}</el-button>
      </template>
    </avue-crud>
    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        width="75%"
        @close="dialog.visible = false"
    >
      <template #header="{ close, titleId, titleClass }">
        <el-button v-if="dialogType === 1"  type="primary" @click="printPage" size="small">打印</el-button>
      </template>
      <div class="card-container" >
        <el-card style="width: 70%" shadow="always">
          <div ref="toPrintRef">
            <el-row style="text-align: center;">
              <el-col :span="24"><el-text tag="b">零、部(组)件领用单</el-text></el-col>
            </el-row>
          <el-row>
            <el-col :span="14" ></el-col>
            <el-col :span="5" ><el-text tag="p" v-if="form.applyCode">{{form.applyCode}}</el-text></el-col>
            <el-col :span="5"></el-col>
          </el-row>
          <el-row style="width: 100%;height: 30px;"></el-row>
          <el-row>
            <el-col :span="2" ><el-text tag="p">领用单位:</el-text></el-col>
            <el-col :span="6" >
              <el-text tag="p" v-if="dialogType === 1 || form.state > 0">{{form.applyOrg}}</el-text>
              <el-input v-else size="small" style="width:150px;padding-bottom: 5px;" v-model="form.applyOrg"/>
            </el-col>
            <el-col :span="2" ><el-text tag="p">发件单位: </el-text></el-col>
            <el-col :span="6" >
              <el-text tag="p" v-if="dialogType === 1 || form.state > 0">{{form.sendOrg}} </el-text>
              <el-input v-else size="small" style="width:150px;padding-bottom: 5px;" v-model="form.sendOrg"/>
            </el-col>
            <el-col :span="2" ><el-text tag="p">工单编号:</el-text></el-col>
            <el-col :span="6">
              <el-text tag="p" v-if="dialogType === 1 || form.state > 0">{{form.workOrderCode}}</el-text>
              <el-select
                  v-else
                  size="small"
                  v-model="form.workOrderCode"
                  placeholder="请选择工单号"
                  clearable
                  style="width:150px;padding-bottom: 5px;"
                  filterable
                  @change="changeOrder"
              >
                <el-option
                    v-for="option in orderList"
                    :key="option.workOrderCode"
                    :label="option.workOrderCode"
                    :value="option.workOrderCode"
                />
              </el-select>
            </el-col>
          </el-row>
          <el-table class="print-table"
              v-loading="loading"
              :data="tableDataList"
              border
          >
            <el-table-column label="序号" type="index" width="60"/>
            <el-table-column label="工作令号" prop="workCode">
              <template v-slot="{row}">
                <el-text v-if="dialogType === 1 || form.state > 0">{{row.workCode}}</el-text>
                <el-input v-else v-model="row.workCode"/>
              </template>
            </el-table-column>
            <el-table-column label="零、部(组)件图号" prop="materialCode" />
            <el-table-column label="名称" prop="materialName" />
            <el-table-column label="数量" align="num">
              <template v-slot="{row}">
                <el-text v-if="dialogType === 1 || form.state > 0">{{row.num}}</el-text>
                <el-input v-else v-model="row.num" type="number"/>
              </template>
            </el-table-column>
            <el-table-column label="实际接收" align="receiveNum" v-if="form.state === '6' || form.state === '8'">
              <template v-slot="{row}">
                <el-text>{{row.receiveNum}}</el-text>
              </template>
            </el-table-column>
            <el-table-column label="备注" align="remark">
              <template v-slot="{row}">
                <el-text v-if="dialogType === 1 || form.state > 0">{{row.remark}}</el-text>
                <el-input v-else v-model="row.remark"/>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="remark" v-if="dialogType !== 1 && form.state === '0'">
              <template v-slot="{row,index}">
                <el-button type="danger" @click="minusItem(row)" icon="el-icon-minus" style="margin-left:15px;width:25px;height:25px;" circle />
              </template>
            </el-table-column>
          </el-table>
          <el-row>
            <el-col :span="2" ><el-text tag="p">领用人:</el-text></el-col>
            <el-col :span="4" ><el-text tag="p" >{{form.applyUser}}</el-text></el-col>
            <el-col :span="2" ><el-text tag="p">审核: </el-text></el-col>
            <el-col :span="4" ><el-text tag="p" >{{form.auditUser}} </el-text></el-col>
            <el-col :span="2" ><el-text tag="p">会签:</el-text></el-col>
            <el-col :span="4" ><el-text tag="p" >{{form.countersignUser}}</el-text></el-col>
            <el-col :span="2" ><el-text tag="p">批准:</el-text></el-col>
            <el-col :span="4" ><el-text tag="p" >{{form.approveUser}}</el-text></el-col>
          </el-row>
          </div>
        </el-card>

        <el-card style="width: 28%" shadow="always">
          <template #header>
            <div class="card-header">
              <span>领用流程</span>
            </div>
            <el-timeline style="max-width: 500px;">
              <el-timeline-item center type="success" placement="top">
                <el-card>
                  <h4>申请</h4>
                  <el-form ref="maintenanceInfoForm2" size="small" :model="form" label-width="auto" style="max-width: 400px">
                    <el-form-item label="领用人员" prop="auditUser">
                      <el-text tag="p" v-if="dialogType === 1 || form.state > 0">{{form.applyUser}}</el-text>
                      <el-select
                          v-else
                          size="small"
                          filterable
                          v-model="form.applyUser"
                          placeholder="请选择领用人员"
                          clearable>
                        <el-option
                            v-for="option in userList"
                            :key="option.userName"
                            :label="option.nickName"
                            :value="option.userName" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="审核人员" v-if="form.state === '0'">
                      <el-text tag="p" v-if="dialogType === 1 || form.state > 0">{{form.auditUser}}</el-text>
                      <el-select
                          v-else
                          size="small"
                          filterable
                          v-model="form.auditUser"
                          placeholder="请选择审核人员"
                          clearable>
                        <el-option
                            v-for="option in userList"
                            :key="option.userName"
                            :label="option.nickName"
                            :value="option.userName" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="申请时间"  v-if="form.state > 0">
                      <el-text tag="p">{{form.created}}</el-text>
                    </el-form-item>
                    <el-form-item style="margin-left: 28%" v-if="dialogType !==1">
                      <el-button type="primary" @click="saveForm(1)" v-if="form.state === '0'">申 请</el-button>
                      <el-button type="success" @click="saveForm(0)" v-if="form.state === '0'">保 存</el-button>
                    </el-form-item>
                  </el-form>
                </el-card>
              </el-timeline-item>
              <el-timeline-item center placement="top"  :type="form.state > 1 ? 'success' : 'primary'">
                <el-card>
                  <h4>审核</h4>
                  <el-form v-if="form.state >= 1"  size="small" :model="form" label-width="auto" style="max-width: 400px">
                    <el-form-item label="审核人员" prop="auditUser">
                      <el-text tag="p">{{form.auditUser}}</el-text>
                    </el-form-item>
                    <el-form-item label="处理结果">
                      <el-text tag="p" v-if="dialogType === 1 || form.state !== '1'">{{form.state === '1' ? '待审核' : form.auditState === 0 ? "通过" : "未通过"}}</el-text>
                      <el-text tag="p" v-else-if="form.auditUser !== username">{{form.auditState ? form.auditState === 0 ? "通过" : "未通过" : "待审核"}}</el-text>
                      <el-radio-group v-else v-model="form.auditState">
                        <el-radio :value=0>通过</el-radio>
                        <el-radio :value=1>不通过</el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item label="会签人员" v-if="dialogType !== 1 && form.state === '1' && form.auditUser === username">
                      <el-select
                          size="small"
                          filterable
                          multiple
                          v-model="form.countersignUsers"
                          placeholder="请选择会签人员"
                          clearable>
                        <el-option
                            v-for="option in userList"
                            :key="option.userName"
                            :label="option.nickName"
                            :value="option.userName" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="审核时间" v-if="form.audit && form.audit.time">
                      <el-text tag="p" >{{form.audit.time}}</el-text>
                    </el-form-item>
                    <el-form-item style="margin-left: 35%">
                      <el-button type="primary" @click="saveForm(2)"  v-if="dialogType !== 1 && form.state === '1' && form.auditUser === username">审 核</el-button>
                    </el-form-item>
                  </el-form>
                </el-card>
              </el-timeline-item>
              <el-timeline-item center placement="top" :type="form.state > 3 ? 'success' : 'primary'">
                <el-card>
                  <h4>会签</h4>
                  <el-form v-if="form.state >= 3"  size="small" :model="form" label-width="auto" style="max-width: 400px">
                    <el-form-item v-for="item of form.countersign" label="会签人员:">
                      <el-text tag="p" >{{item.user}}--</el-text>
                      <el-text tag="p" v-if="dialogType === 1  ||  item.user !== username">{{item.state === -1 ? '未审核' : item.state === 0 ? '通过' : '未通过'}}</el-text>
                      <el-text tag="p" v-else-if="item.state !== -1 && item.user === username">{{item.state === 0 ? '通过' : '未通过'}}</el-text>
                      <el-radio-group v-model="form.countersignState" v-if="dialogType !== 1  && item.state === -1 && item.user === username">
                        <el-radio :value=0>通过</el-radio>
                        <el-radio :value=1>不通过</el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item label="批准人员" v-if="dialogType !== 1  && form.countersignOk && form.state === '3'">
                      <el-select
                          size="small"
                          v-model="form.approveUser"
                          placeholder="请选择批准人员"
                          clearable >
                        <el-option
                            v-for="option in userList"
                            :key="option.userName"
                            :label="option.nickName"
                            :value="option.userName" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="通过时间" v-if="form.countersignInfo && form.countersignInfo.time">
                      <el-text tag="p" >{{form.countersignInfo.time}}</el-text>
                    </el-form-item>
                    <el-form-item style="margin-left: 35%">
                      <el-button type="primary" v-if="dialogType !== 1 && form.state === '3' && form.countersignUser.includes(username) && form.countersignBtn" @click="saveForm(3)">审 核</el-button>
                    </el-form-item>
                  </el-form>
                </el-card>
              </el-timeline-item>
              <el-timeline-item center placement="top" :type="form.state > 5 ? 'success' : 'primary'">
                <el-card>
                  <h4>批准</h4>
                  <el-form v-if="form.state >= 5" size="small" :model="form" label-width="auto" style="max-width: 400px">
                    <el-form-item label="审批人" v-if="form.state > 5">
                      <el-text tag="p">{{form.approve.user}}</el-text>
                    </el-form-item>
                    <el-form-item label="审批结果">
                      <el-text tag="p" v-if="dialogType === 1 || form.state === '6' || form.state === '7'">{{form.state === '5' ?  '待审批' : form.state === '6' ? '通过' : '未通过'}}</el-text>
                      <el-text tag="p" v-else-if="form.approveUser !== username">待审批</el-text>
                      <el-radio-group v-else v-model="form.approveState">
                        <el-radio :value=0>通过</el-radio>
                        <el-radio :value=1>不通过</el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item label="审批时间" v-if="form.state > 5">
                      <el-text tag="p">{{form.approve.time}}</el-text>
                    </el-form-item>
                    <el-form-item style="margin-left: 35%">
                      <el-button type="primary" @click="saveForm(4)" v-if="dialogType !== 1 && form.state === '5' && form.approveUser === username">审 核</el-button>
                    </el-form-item>
                  </el-form>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </template>
        </el-card>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { useUserStoreHook } from "@/store/index";
import { ref, getCurrentInstance } from "vue";
import { html2CanvasPrint } from "@/utils/common";
import { useCrud } from "@/hooks/userCrud";
import dictDataUtil from "@/common/configs/dictDataUtil";
import {queryApplyInfoDetails,queryWorkOrderList,saveApplyInfoDetails,auditApplyInfoDetails} from "@/api/order"
import {getUserList} from "@/api/system/user"
import { useCommonStoreHook } from "@/store";
const { isShowTable, tableType } = toRefs(useCommonStoreHook());
const test = () => {
  isShowTable.value = true;
  tableType.value = tableType.value == 1 ? 2 : 1;
};

// 1.定义ref
const toPrintRef = ref(null);
// 传入一个url，后面不带/
const { form, data, option, search, page, toDeleteIds, Methords, Utils } =
  useCrud({
    src: "/api/v1/plan/requisition",
  });
const { dataList, createRow, updateRow, deleteRow, searchChange, resetChange } = Methords; //增删改查
const { selectionChange, multipleDelete } = Methords; //选中和批量删除事件
const { checkBtnPerm, downloadTemplate, exportData } = Utils; //按钮权限等工具
const { username } = useUserStoreHook().user;
const minusItem =(row)=>{
  tableDataList.value = tableDataList.value.filter(item=>item.id !== row.id)
}
const changeOrder =(val)=>{
  queryApplyInfoDetails({workOrderCode: val}).then((data)=>{
    tableDataList.value = data.data
  })
}
const saveForm = (type) =>{
  let state = type;
  let step = null;
  let nextUsers = ""
  if(type === 1 || type === 0){
    if(tableDataList.value.length === 0){
      ElMessage.error("当前没有申请的物料信息")
      return;
    }
    for(let item of tableDataList.value){
      if(!item.workCode){
        ElMessage.error("工作令号不能为空")
        return;
      }
      if(!item.num || item.num <=0){
        ElMessage.error("物料数量不正确")
        return;
      }
    }
    if(!form.value.applyUser){
      ElMessage.error("领用人员不能为空")
      return;
    }
    if(!form.value.auditUser){
      ElMessage.error("审核人员不能为空")
      return;
    }
    const params = {...form.value,'state': state,details: tableDataList.value}
    saveApplyInfoDetails(params).then((data)=>{
      if(data.code === '200'){
        ElMessage.success(data.msg)
        dialog.visible = false
        dataList()
      }else{
        ElMessage.error(data.msg)
      }
    })
    return;
  }
  step = "audit";
  if(type === 2){
    if(form.value.auditState != undefined){
      if(form.value.auditState === 0 && form.value.countersignUsers.length === 0){
        ElMessage.error("会签人员不能为空")
        return;
      }
    }else{
      if(!form.value.auditState){
        ElMessage.error("请选择处理结果")
        return;
      }
    }
    nextUsers = form.value.countersignUsers.join(",")
    state = form.value.auditState
  }
  if(type === 3){
    step = "countersign";
    if(!form.value.approveUser && form.value.countersignOk){
      ElMessage.error("请选择审批人员")
      return;
    }
    if(form.value.countersignState === undefined){
      ElMessage.error("请选择处理结果")
      return;
    }
    nextUsers = form.value.approveUser
    state = form.value.countersignState
  }
  if(type === 4){
    step = "approve";
    if(form.value.approveState === undefined){
      ElMessage.error("请选择处理结果")
      return;
    }
    state = form.value.approveState
  }
  const params = {id: form.value.id,'state': state,currentStep: step,nextUser: nextUsers}
  auditApplyInfoDetails(params).then((data)=>{
    if(data.code === '200'){
      ElMessage.success(data.msg)
      dialog.visible = false
      dataList()
    }else{
      ElMessage.error(data.msg)
    }
  })
}
const loading = ref(false)
const crudRef = ref(null); //crudRef.value 获取avue-crud对象
const userList = ref([])
const orderList = ref([])
const dialogType = ref(false)
const dialog = reactive({
  title: "领用单",
  visible: false,
});
const tableDataList = ref([])
const openDialog = (type,row)=>{
  dialogType.value = type
  tableDataList.value = []
  form.value = {}
  form.value.sendOrg = "周转库";
  form.value.applyOrg = "制造中心"
  form.value.state = "0"
  if(type !== 0){
    queryApplyInfoDetails({applyCode: row.applyCode}).then((data)=>{
      tableDataList.value = data.data
    })
    form.value = row
  }
  form.value.countersign = []
  if(row && row.flowInfo){
    let json = JSON.parse(row.flowInfo)
    let auditInfo = json.audit
    if(auditInfo){
      form.value.audit =auditInfo.info
      form.value.auditState = form.value.audit.state
    }
    if(row.countersignUser){
      form.value.countersignUsers = row.countersignUser.split(",")
    }
    form.value.countersignBtn = false
    if(json.countersign){
      form.value.countersign = json.countersign.list
      form.value.countersignInfo = json.countersign.info
      //当断当前是否最后一个
      let isOk = true
      for(let obj of form.value.countersign){
        if(obj.state === -1 && obj.user === username){
          form.value.countersignBtn = true
        }
        if(obj.user !== username && obj.state === -1){
          isOk = false
        }
      }
      form.value.countersignOk = isOk;
    }
    if(json.approve){
      form.value.approve = json.approve.info
    }
    form.value.approveUser = row.approveUser
  }
  dialog.visible = true
  getUserList({}).then((data)=>{
    userList.value = data.data
  })
}
const printPage = ()=>{
  html2CanvasPrint(toPrintRef.value);
}
// 设置表格列或者其他自定义的option
option.value = Object.assign(option.value, {
  delBtn: false,
  addBtn: false,
  editBtn: false,
  viewBtn: false,
  selection: true,
  column: [
    {
      label: "领用单号",
      prop: "applyCode",
      search: true,
      width: 150,
      overHidden: true,
    },
    {
      label: "工单单号",
      prop: "workOrderCode",
      search: true,
      width: 150,
      overHidden: true,
    },
    {
      label: "计划单号",
      prop: "orderCode",
      search: true,
      width: 150,
      overHidden: true,
    },
    {
      label: "领用单位",
      prop: "applyOrg",
      width: 150,
      overHidden: true,
    },
    {
      label: "发件单位",
      prop: "sendOrg",
      width: 150,
      overHidden: true,
    },
    {
      label: "领用人员",
      prop: "applyUser",
      width: 150,
      overHidden: true,
      search: true,
    },
    {
      label: "审核人员",
      prop: "auditUser",
      width: 150,
      overHidden: true,
    },
    {
      label: "会签人员",
      width: 150,
      overHidden: true,
      prop: "countersignUser",
    },
    {
      label: "审批人员",
      width: 150,
      overHidden: true,
      prop: "approveUser",
    },
    {
      label: "状态",
      prop: "state",
      width: 150,
      type: 'select',
      dicUrl: dictDataUtil.request_url + dictDataUtil.TYPE_CODE.requisition_state,
      props: {
        label: "dictLabel", // 下拉菜单显示的字段
        value: "dictValue" // 下拉菜单值的字
      },
    },
    {
      label: "创建时间",
      prop: "created",
      width: 160,
      display: false
    },
  ],
});

onMounted(() => {
  queryWorkOrderList({}).then((data)=>{
    if(!data.data){
      ElMessage.warning("请维护物料BOM")
    }
    orderList.value = data.data
  })
  // console.log("crudRef", crudRef)
  dataList();
});
</script>



<style scoped>
:deep(.card-container .el-form-item) {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 15px; /* 根据需要调整高度 */
}

:deep(.el-timeline-item){
  padding-bottom: 0px;
  position: relative;
}
.card-container {
  display: flex;
  justify-content: space-around;
}
</style>
