<template>
  <div class="p-2">
    <el-card shadow="never">
      <!-- mode用于直接后端发起流程 不同接口实现方式可查看具体后端代码 -->
      <!-- 默认前端发起 前端发起更多样性 比如可以选审批人 选抄送人 上传附件等等 后端发起需要用户自行编写代码传这些参数 -->
      <approvalButton
        @submitForm="submitForm"
        @approvalVerifyOpen="approvalVerifyOpen"
        @handleApprovalRecord="handleApprovalRecord"
        :buttonLoading="buttonLoading"
        :id="form.inStockBillId"
        :status="form.flowStatus"
        :pageType="routeParams.type"
        :mode="false"
      />

      <el-card shadow="never" style="height: 78vh; overflow-y: auto">
        <el-form ref="addFormRef" :model="form" :rules="rules" label-width="120px" :disabled="true">
          <el-row>
            <el-col :span="12">
              <el-form-item label="入库单号" prop="inStockCode">
                <el-input v-model="form.inStockCode" placeholder="请输入入库单号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入库单类型" prop="inStockType">
                <el-select v-model="form.inStockType" placeholder="请选择入库单类型">
                  <el-option v-for="dict in wms_in_stock_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="关联单号" prop="inventoryAmount">
                <el-input v-model="form.inventoryAmount" placeholder="请输入关联单号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="供应商" prop="supplier">
                <el-input v-model="form.supplierName" placeholder="请输入供应商" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="联系人" prop="contactUser">
                <el-input v-model="form.contactUser" placeholder="请输入联系人" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="contactNumber">
                <el-input v-model="form.contactNumber" placeholder="请输入联系电话" />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 全宽字段 -->
          <el-form-item label="入库说明" prop="directions">
            <el-input v-model="form.directions" type="textarea" :rows="3" placeholder="请输入入库说明" style="width: 100%" />
          </el-form-item>

          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="请输入备注" style="width: 100%" />
          </el-form-item>
        </el-form>

        <div>
          <el-card>
            <template #header>
              <div>物料情况</div>
            </template>
            <div v-if="selectedMaterials.length > 0" style="margin-top: 20px">
              <el-table :data="selectedMaterials" border style="width: auto">
                <el-table-column prop="materialCode" align="center" label="物料编码" />
                <el-table-column prop="materialName" align="center" label="物料名称" />
                <el-table-column prop="materialBrand" align="center" label="品牌" />
                <el-table-column prop="materialModel" align="center" label="型号" />
                <el-table-column prop="batchNumber" align="center" label="批次号" />
                <el-table-column prop="unitPrice" align="center" label="单价(元)" />
                <el-table-column prop="inStockAmount" align="center" label="入库数量" />
                <el-table-column prop="unitName" align="center" label="单位" />
                <el-table-column prop="totalPrice" align="center" label="总价(元)" />
              </el-table>
            </div>
          </el-card>
        </div>
      </el-card>
      <!-- 提交组件 -->
      <submitVerify ref="submitVerifyRef" :task-variables="taskVariables" @submit-callback="submitCallback" />
      <!-- 审批记录 -->
      <approvalRecord ref="approvalRecordRef" />
    </el-card>
  </div>
</template>

<script setup name="Leave" lang="ts">
import { startWorkFlow } from '@/api/workflow/task';
import SubmitVerify from '@/components/Process/submitVerify.vue';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';
import ApprovalButton from '@/components/Process/approvalButton.vue';
import { StartProcessBo } from '@/api/workflow/workflowCommon/types';
import { getInStockBill, submitFlowData } from '@/api/wms/inStockBill';
import { getWmsInStockDetailsList } from '@/api/wms/inStockDetails';
import type { ComponentInternalInstance } from 'vue';
import { getCurrentInstance, nextTick, onMounted, reactive, ref, toRefs } from 'vue';
import { InStockBillForm, InStockBillQuery } from '@/api/wms/inStockBill/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { wms_in_stock_type, wms_in_stock_bill_status } = toRefs<any>(proxy?.useDict('wms_in_stock_type', 'wms_in_stock_bill_status'));

// import type { ElFormInstance } from 'element-plus';

const buttonLoading = ref(false);
const loading = ref(true);
const leaveTime = ref<Array<string>>([]);
//路由参数
const routeParams = ref<Record<string, any>>({});
// 自定义流程可不选择 直接填写flowCode 例如 'leave1'
const flowCode = ref<string>('wms_in');
//提交组件
const submitVerifyRef = ref<InstanceType<typeof SubmitVerify>>();
//审批记录组件
const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();

const leaveFormRef = ref<ElFormInstance>();

const submitFormData = ref<StartProcessBo>({
  businessId: '',
  flowCode: '',
  variables: {},
  bizExt: {}
});
const taskVariables = ref<Record<string, any>>({});
const flowInstanceBizExtBo = ref<Record<string, any>>({});

const initFormData: InStockBillForm = {
  inStockBillId: undefined,
  inStockCode: undefined,
  inStockType: undefined,
  projectId: undefined,
  inventoryAmount: undefined,
  supplierName: undefined,
  contactUser: undefined,
  contactNumber: undefined,
  directions: undefined,
  inStockBillStatus: undefined,
  flowStatus: undefined,
  warehouseId: undefined,
  remark: undefined
};
const data = reactive<PageData<InStockBillForm, InStockBillQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    startLeaveDays: undefined,
    endLeaveDays: undefined
  },
  rules: {}
});

const { form, rules } = toRefs(data);

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  leaveTime.value = [];
  leaveFormRef.value?.resetFields();
};

const changeLeaveTime = () => {
  const startDate = new Date(leaveTime.value[0]).getTime();
  const endDate = new Date(leaveTime.value[1]).getTime();
  const diffInMilliseconds = endDate - startDate;
  form.value.leaveDays = Math.floor(diffInMilliseconds / (1000 * 60 * 60 * 24)) + 1;
};

const selectedMaterials = ref([]);
/** 获取详情 */
const getInfo = () => {
  loading.value = true;
  buttonLoading.value = false;

  nextTick(async () => {
    const id = routeParams.value.id;
    const res = await getInStockBill(id);
    Object.assign(form.value, res.data);

    const childList = await getWmsInStockDetailsList({ inStockBillId: id });
    selectedMaterials.value = childList.data;

    // leaveTime.value = [];
    // leaveTime.value.push(form.value.startDate);
    // leaveTime.value.push(form.value.endDate);
    loading.value = false;
    buttonLoading.value = false;
  });
};

/** 提交按钮*/
const submitForm = (status: string, mode: boolean) => {
  if (status === 'submit') {
    const res = submitFlowData(form.value).finally(() => (buttonLoading.value = false));
    form.value = res.data;
    buttonLoading.value = false;
    proxy?.$modal.msgSuccess('操作成功');
    proxy.$tab.closePage(proxy.$route);
    proxy.$router.go(-1);
    // handleStartWorkFlow();
    return;
  }

  proxy.$tab.closePage(proxy.$route);
  proxy.$router.go(-1);

  console.log('submitForm', status, mode);
};

//提交申请
const handleStartWorkFlow = async () => {
  try {
    submitFormData.value.flowCode = flowCode.value;
    submitFormData.value.businessId = data.id;

    //流程实例业务扩展字段
    flowInstanceBizExtBo.value = {
      businessTitle: '物料入库流程',
      businessCode: data.applyCode
    };
    submitFormData.value.variables = taskVariables.value;
    submitFormData.value.bizExt = flowInstanceBizExtBo.value;
    const resp = await startWorkFlow(submitFormData.value);
    if (submitVerifyRef.value) {
      buttonLoading.value = false;
      submitVerifyRef.value.openDialog(resp.data.taskId);
    }
  } finally {
    buttonLoading.value = false;
  }
};
//审批记录
const handleApprovalRecord = () => {
  approvalRecordRef.value.init(form.value.id);
};
//提交回调
const submitCallback = async () => {
  await proxy.$tab.closePage(proxy.$route);
  proxy.$router.go(-1);
};
//审批
const approvalVerifyOpen = async () => {
  submitVerifyRef.value.openDialog(routeParams.value.taskId);
};

onMounted(() => {
  nextTick(async () => {
    routeParams.value = proxy.$route.query;
    reset();
    loading.value = false;
    // routeParams.value.type = 'update';
    // if (routeParams.value.type === 'update' || routeParams.value.type === 'view' || routeParams.value.type === 'approval') {
    getInfo();
    // }
  });
});
</script>
