<template>
  <div class='p-2'>
    <transition :enter-active-class='proxy?.animate.searchAnimate.enter'
                :leave-active-class='proxy?.animate.searchAnimate.leave'>
      <div v-show='showSearch' class='mb-[10px]'>
        <el-card shadow='hover'>
          <el-form ref='queryFormRef' :model='queryParams' :inline='true'>
            <el-form-item label='订单编号' prop='orderCode'>
              <el-input v-model='queryParams.orderCode' placeholder='请输入订单编号' clearable @keyup.enter='handleQuery' />
            </el-form-item>
<!--            <el-form-item label='订单类型' prop='orderType'>-->
<!--              <el-select v-model='queryParams.orderType' placeholder='请选择订单类型' clearable>-->
<!--                <el-option v-for='dict in mes_order_type' :key='dict.value' :label='dict.label' :value='dict.value' />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--            <el-form-item label='计划开始时间' prop='planBeginTime'>-->
<!--              <el-date-picker clearable-->
<!--                              v-model='queryParams.planBeginTime'-->
<!--                              type='date'-->
<!--                              value-format='YYYY-MM-DD'-->
<!--                              placeholder='请选择计划开始时间'-->
<!--              />-->
<!--            </el-form-item>-->
            <el-form-item label='订单状态' prop='orderStatus'>
              <el-select v-model='queryParams.orderStatus' placeholder='请选择订单状态' clearable>
                <el-option v-for='dict in mes_order_status' :key='dict.value' :label='dict.label' :value='dict.value' />
              </el-select>
            </el-form-item>
<!--            <el-form-item label='库存锁定标识' prop='stockLockFlag'>-->
<!--              <el-select v-model='queryParams.stockLockFlag' placeholder='请选择库存锁定标识' clearable>-->
<!--                <el-option v-for='dict in mes_stock_lock_flag' :key='dict.value' :label='dict.label'-->
<!--                           :value='dict.value' />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--            <el-form-item label='完成标识' prop='finishFlag'>-->
<!--              <el-select v-model='queryParams.finishFlag' placeholder='请选择完成标识' clearable>-->
<!--                <el-option v-for='dict in mes_finish_flag' :key='dict.value' :label='dict.label' :value='dict.value' />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--            <el-form-item label='下达工单' prop='releaseFlag'>-->
<!--              <el-select v-model='queryParams.releaseFlag' placeholder='请选择下达工单' clearable>-->
<!--                <el-option v-for='dict in mes_release_flag' :key='dict.value' :label='dict.label' :value='dict.value' />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
            <el-form-item>
              <el-button type='primary' icon='Search' @click='handleQuery'>搜索</el-button>
              <el-button icon='Refresh' @click='resetQuery'>重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow='never'>
      <template #header>
        <el-row :gutter='10' class='mb8'>
          <el-col :span='1.5'>
            <el-button type='primary' plain icon='Plus' @click='handleAdd' v-hasPermi="['mes:orderInfo:add']">新增
            </el-button>
          </el-col>
          <el-col :span='1.5'>
            <el-button type='success' plain icon='Edit' :disabled='single' @click='handleUpdate()'
                       v-hasPermi="['mes:orderInfo:edit']">修改
            </el-button>
          </el-col>
          <el-col :span='1.5'>
            <el-button type='danger' plain icon='Delete' :disabled='multiple' @click='handleDelete()'
                       v-hasPermi="['mes:orderInfo:remove']">删除
            </el-button>
          </el-col>
          <el-col :span='1.5'>
            <el-button type='warning' plain icon='Download' @click='handleExport' v-hasPermi="['mes:orderInfo:export']">
              导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch='showSearch' :columns='columns' :search='true'
                         @queryTable='getList'></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading='loading' :data='orderInfoList' @selection-change='handleSelectionChange'>
        <el-table-column type='selection' width='55' align='center' />
        <el-table-column label='主键标识' align='center' prop='productOrderId' v-if='columns[0].visible' />
        <el-table-column label='订单编号' align='center' prop='orderCode' v-if='columns[2].visible' />
        <el-table-column label='销售订单ID' align='center' prop='saleOrderId' v-if='columns[3].visible' />
        <el-table-column label='项目编号' align='center' prop='projectNo' v-if='columns[4].visible' />
        <el-table-column label='订单类型' align='center' prop='orderType' v-if='columns[5].visible'>
          <template #default='scope'>
            <dict-tag :options='mes_order_type' :value='scope.row.orderType' />
          </template>
        </el-table-column>
        <el-table-column label='成品名称' align='center' prop='materialName' v-if='columns[6].visible' width='160' />
        <el-table-column label='物料BOM' align='center' prop='materialBomId' v-if='columns[7].visible' width='100' />
        <el-table-column label='派工类型' align='center' prop='dispatchType' v-if='columns[8].visible'>
          <template #default='scope'>
            <dict-tag :options='mes_dispatch_type' :value='scope.row.dispatchType' />
          </template>
        </el-table-column>
        <el-table-column :label='dispatchTypeName' align='center' prop='dispatchName' v-if='columns[9].visible' />
        <el-table-column label='销售数量' align='center' prop='saleAmount' v-if='columns[10].visible' />
        <el-table-column label='计划交货日期' align='center' prop='planDeliveryDate' width='180' v-if='columns[11].visible'>
          <template #default='scope'>
            <span>{{ parseTime(scope.row.planDeliveryDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label='计划数量' align='center' prop='planAmount' v-if='columns[12].visible' />
        <el-table-column label='已派工数量' align='center' prop='dispatchAmount' v-if='columns[13].visible' />
        <el-table-column label='完成数量' align='center' prop='completeAmount' v-if='columns[14].visible' />
        <el-table-column label='发布时间' align='center' prop='releaseTime' width='180' v-if='columns[15].visible'>
          <template #default='scope'>
            <span>{{ parseTime(scope.row.releaseTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label='计划开始时间' align='center' prop='planBeginTime' width='180' v-if='columns[16].visible'>
          <template #default='scope'>
            <span>{{ parseTime(scope.row.planBeginTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label='计划结束时间' align='center' prop='planEndTime' width='180' v-if='columns[17].visible'>
          <template #default='scope'>
            <span>{{ parseTime(scope.row.planEndTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label='实际开始时间' align='center' prop='realBeginTime' width='180' v-if='columns[18].visible'>
          <template #default='scope'>
            <span>{{ parseTime(scope.row.realBeginTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label='实际完成时间' align='center' prop='realEndTime' width='180' v-if='columns[19].visible'>
          <template #default='scope'>
            <span>{{ parseTime(scope.row.realEndTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label='订单状态' align='center' prop='orderStatus' v-if='columns[20].visible'>
          <template #default='scope'>
            <dict-tag :options='mes_order_status' :value='scope.row.orderStatus' />
          </template>
        </el-table-column>
        <el-table-column label='库存锁定标识' align='center' prop='stockLockFlag' v-if='columns[21].visible'>
          <template #default='scope'>
            <dict-tag :options='mes_stock_lock_flag' :value='scope.row.stockLockFlag' />
          </template>
        </el-table-column>
        <el-table-column label='前置生产订单ID' align='center' prop='preOrderId' v-if='columns[22].visible' />
        <el-table-column label='前置订单编号' align='center' prop='preOrderCode' v-if='columns[23].visible' />
        <el-table-column label='完成标识' align='center' prop='finishFlag' v-if='columns[24].visible'>
          <template #default='scope'>
            <dict-tag :options='mes_finish_flag' :value='scope.row.finishFlag' />
          </template>
        </el-table-column>
        <el-table-column label='下达工单' align='center' prop='releaseFlag' v-if='columns[25].visible' width='80'>
          <template #default='scope'>
            <dict-tag :options='mes_release_flag' :value='scope.row.releaseFlag' />
          </template>
        </el-table-column>
        <el-table-column label='订单版本' align='center' prop='orderVersion' v-if='columns[26].visible' />
        <el-table-column label='工厂ID' align='center' prop='factoryId' v-if='columns[27].visible' />
        <el-table-column label='备注' align='center' prop='remark' v-if='columns[28].visible' />
        <el-table-column label='操作' align='center' class-name="small-padding fixed-width"  fixed="right">
          <template #default='scope'>
            <el-button
              size="small"
              type="text"
              icon="el-icon-user-solid"
              @click="handleDispatch(scope.row)"
              v-if="1===1"
              v-hasPermi="['mes:orderInfo:edit']"
            >生产派工
            </el-button>
<!--            <el-tooltip content='删除' placement='top'>-->
<!--              <el-button link type='primary' icon='Delete' @click='handleDelete(scope.row)'-->
<!--                         v-hasPermi="['mes:orderInfo:remove']"></el-button>-->
<!--            </el-tooltip>-->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show='total > 0' :total='total' v-model:page='queryParams.pageNum'
                  v-model:limit='queryParams.pageSize' @pagination='getList' />
    </el-card>
    <!-- 添加或修改生产订单信息对话框 -->
    <el-dialog :title='dialog.title' v-model='dialog.visible' width='500px' append-to-body>
      <el-form ref='orderInfoFormRef' :model='form' :rules='rules' label-width='100px'>
<!--        <el-form-item label='订单编号' prop='orderCode'>-->
<!--          <el-input v-model='form.orderCode' placeholder='请输入订单编号' />-->
<!--        </el-form-item>-->
        <el-form-item label='订单版本' prop='orderVersion'>
          <el-input v-model='form.orderVersion' placeholder='请输入订单版本' />
        </el-form-item>
<!--        <el-form-item label='销售订单ID' prop='saleOrderId'>-->
<!--          <el-input v-model='form.saleOrderId' placeholder='请输入销售订单ID' />-->
<!--        </el-form-item>-->
<!--        <el-form-item label='项目编号' prop='projectNo'>-->
<!--          <el-input v-model='form.projectNo' placeholder='请输入项目编号' />-->
<!--        </el-form-item>-->
        <el-form-item label='订单类型' prop='orderType'>
          <el-radio-group v-model='form.orderType'>
            <el-radio
              v-for='dict in mes_order_type'
              :key='dict.value'
              :value='dict.value'
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label='成品名称' prop='materialId'>
          <el-input v-model='form.materialId' placeholder='请输入成品名称' />
        </el-form-item>
        <el-form-item label='物料BOM' prop='materialBomId'>
          <el-input v-model='form.materialBomId' placeholder='请输入物料BOM' />
        </el-form-item>
        <el-form-item label='派工类型' prop='dispatchType'>
          <el-radio-group v-model='form.dispatchType' :disabled="true">
            <el-radio
              v-for='dict in mes_dispatch_type'
              :key='dict.value'
              :value='dict.value'
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label='dispatchTypeName' prop='dispatchId'>
          <el-select v-model="form.dispatchId" placeholder="请选择">
            <el-option
              v-for="item in dispatchTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label='销售数量' prop='saleAmount'>-->
<!--          <el-input v-model='form.saleAmount' placeholder='请输入销售数量' />-->
<!--        </el-form-item>-->
        <el-form-item label='计划交货日期' prop='planDeliveryDate'>
          <el-date-picker clearable
                          v-model='form.planDeliveryDate'
                          type='datetime'
                          value-format='YYYY-MM-DD HH:mm:ss'
                          placeholder='请选择计划交货日期'>
          </el-date-picker>
        </el-form-item>
        <el-form-item label='计划数量' prop='planAmount' >
          <el-input-number v-model='form.planAmount' placeholder='请输入计划数量' style="width: 200px;"/>
        </el-form-item>
<!--        <el-form-item label='已派工数量' prop='dispatchAmount'>-->
<!--          <el-input v-model='form.dispatchAmount' placeholder='请输入已派工数量' />-->
<!--        </el-form-item>-->
        <el-form-item label='计划开始时间' prop='planBeginTime'>
          <el-date-picker clearable
                          v-model='form.planBeginTime'
                          type='datetime'
                          value-format='YYYY-MM-DD HH:mm:ss'
                          placeholder='请选择计划开始时间'>
          </el-date-picker>
        </el-form-item>
        <el-form-item label='计划结束时间' prop='planEndTime'>
          <el-date-picker clearable
                          v-model='form.planEndTime'
                          type='datetime'
                          value-format='YYYY-MM-DD HH:mm:ss'
                          placeholder='请选择计划结束时间'>
          </el-date-picker>
        </el-form-item>
<!--        <el-form-item label='库存锁定标识' prop='stockLockFlag'>-->
<!--          <el-radio-group v-model='form.stockLockFlag'>-->
<!--            <el-radio-->
<!--              v-for='dict in mes_stock_lock_flag'-->
<!--              :key='dict.value'-->
<!--              :value='dict.value'-->
<!--            >{{ dict.label }}-->
<!--            </el-radio>-->
<!--          </el-radio-group>-->
<!--        </el-form-item>-->
        <el-form-item label='备注' prop='remark'>
          <el-input v-model='form.remark' placeholder='请输入备注' />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class='dialog-footer'>
          <el-button :loading='buttonLoading' type='primary' @click='submitForm'>确 定</el-button>
          <el-button @click='cancel'>取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name='OrderInfo' lang='ts'>
import { listOrderInfo, getOrderInfo, delOrderInfo, addOrderInfo, updateOrderInfo } from '@/api/mes/orderInfo';
import { OrderInfoVO, OrderInfoQuery, OrderInfoForm } from '@/api/mes/orderInfo/types';
import { getProcessInfoList } from '@/api/mes/baseProcessInfo';
import { getBaseRouteList } from '@/api/mes/baseRoute';
import { getProdLineList } from '@/api/mes/baseProdLineInfo';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const {
  mes_order_status,
  mes_stock_lock_flag,
  mes_dispatch_type,
  mes_finish_flag,
  mes_order_type,
  mes_release_flag
} = toRefs<any>(proxy?.useDict('mes_order_status', 'mes_stock_lock_flag', 'mes_dispatch_type', 'mes_finish_flag', 'mes_order_type', 'mes_release_flag'));

const orderInfoList = ref<OrderInfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const orderInfoFormRef = ref<ElFormInstance>();
/** 下拉框查询派工类型信息列表 */
const dispatchTypeList = ref([])
const dispatchTypeName = ref("");

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `主键标识`, visible: false },
  { key: 1, label: `租户编号`, visible: false },
  { key: 2, label: `订单编号`, visible: true },
  { key: 3, label: `销售订单ID`, visible: false },
  { key: 4, label: `项目编号`, visible: true },
  { key: 5, label: `订单类型`, visible: true },
  { key: 6, label: `成品名称`, visible: true },
  { key: 7, label: `物料BOM`, visible: true },
  { key: 8, label: `派工类型`, visible: true },
  { key: 9, label: `派工ID`, visible: true },
  { key: 10, label: `销售数量`, visible: false },
  { key: 11, label: `计划交货日期`, visible: true },
  { key: 12, label: `计划数量`, visible: true },
  { key: 13, label: `已派工数量`, visible: false },
  { key: 14, label: `完成数量`, visible: true },
  { key: 15, label: `发布时间`, visible: false },
  { key: 16, label: `计划开始时间`, visible: true },
  { key: 17, label: `计划结束时间`, visible: true },
  { key: 18, label: `实际开始时间`, visible: true },
  { key: 19, label: `实际完成时间`, visible: true },
  { key: 20, label: `订单状态`, visible: true },
  { key: 21, label: `库存锁定标识`, visible: false },
  { key: 22, label: `前置生产订单ID`, visible: false },
  { key: 23, label: `前置订单编号`, visible: false },
  { key: 24, label: `完成标识`, visible: true },
  { key: 25, label: `下达工单`, visible: true },
  { key: 26, label: `订单版本`, visible: false },
  { key: 27, label: `工厂ID`, visible: false },
  { key: 28, label: `备注`, visible: false },
  { key: 29, label: `创建部门`, visible: false },
  { key: 30, label: `创建人`, visible: false },
  { key: 31, label: `创建时间`, visible: false },
  { key: 32, label: `更新人`, visible: false },
  { key: 33, label: `更新时间`, visible: false }
]);

const initFormData: OrderInfoForm = {
  productOrderId: undefined,
  orderCode: undefined,
  saleOrderId: undefined,
  projectNo: undefined,
  orderType: '1',
  materialId: undefined,
  materialBomId: undefined,
  dispatchType: undefined,
  dispatchId: undefined,
  saleAmount: undefined,
  planDeliveryDate: undefined,
  planAmount: 1,
  dispatchAmount: undefined,
  completeAmount: undefined,
  releaseTime: undefined,
  planBeginTime: undefined,
  planEndTime: undefined,
  realBeginTime: undefined,
  realEndTime: undefined,
  orderStatus: undefined,
  stockLockFlag: undefined,
  preOrderId: undefined,
  preOrderCode: undefined,
  finishFlag: undefined,
  releaseFlag: undefined,
  orderVersion: undefined,
  factoryId: undefined,
  remark: undefined
};
const data = reactive<PageData<OrderInfoForm, OrderInfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productOrderId: undefined,
    orderCode: undefined,
    saleOrderId: undefined,
    projectNo: undefined,
    orderType: undefined,
    materialId: undefined,
    materialBomId: undefined,
    dispatchType: undefined,
    dispatchId: undefined,
    saleAmount: undefined,
    planDeliveryDate: undefined,
    planAmount: undefined,
    dispatchAmount: undefined,
    completeAmount: undefined,
    releaseTime: undefined,
    planBeginTime: undefined,
    planEndTime: undefined,
    realBeginTime: undefined,
    realEndTime: undefined,
    orderStatus: undefined,
    stockLockFlag: undefined,
    preOrderId: undefined,
    preOrderCode: undefined,
    finishFlag: undefined,
    releaseFlag: undefined,
    orderVersion: undefined,
    factoryId: undefined,
    params: {}
  },
  rules: {
    planAmount: [
      { required: true, message: '计划数量不能为空', trigger: 'blur' }
    ],
  }
});

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

/** 查询生产订单信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listOrderInfo(queryParams.value);
  orderInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

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

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: OrderInfoVO[]) => {
  ids.value = selection.map(item => item.productOrderId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加生产订单信息';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: OrderInfoVO) => {
  reset();
  const _productOrderId = row?.productOrderId || ids.value[0];
  const res = await getOrderInfo(_productOrderId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改生产订单信息';
};

/** 提交按钮 */
const submitForm = () => {
  orderInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.productOrderId) {
        await updateOrderInfo(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addOrderInfo(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: OrderInfoVO) => {
  const _productOrderIds = row?.productOrderId || ids.value;
  await proxy?.$modal.confirm('是否确认删除生产订单信息编号为"' + _productOrderIds + '"的数据项？').finally(() => loading.value = false);
  await delOrderInfo(_productOrderIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('mes/orderInfo/export', {
    ...queryParams.value
  }, `orderInfo_${new Date().getTime()}.xlsx`);
};

onMounted(() => {
  getList();
  dispatchTypeFunction();  //派工类型(1产线 2工艺路线 3工序)
});

const dispatchTypeFunction = async () => {
  const dispatchTypeRes = await proxy?.getConfigKey('sys.orderInfo.dispatchType');
  initFormData.dispatchType = dispatchTypeRes.data;
  if (dispatchTypeRes.data === '1'){
    dispatchTypeName.value = "产线";
    const res = await getProdLineList(null);
    dispatchTypeList.value = res.data.map(item => ({
      id: item.prodLineId,
      name: item.prodLineName
    }));
  } else if (dispatchTypeRes.data === '2'){
    dispatchTypeName.value = "工艺路线";
    const res = await getBaseRouteList(null);
    dispatchTypeList.value = res.data.map(item => ({
      id: item.routeId,
      name: item.routeName
    }));
  } else if (dispatchTypeRes.data === '3'){
    dispatchTypeName.value = "工序";
    const res = await getProcessInfoList(null);
    dispatchTypeList.value = res.data.map(item => ({
      id: item.processId,
      name: item.processName
    }));
  }
};

const handleDispatch = (row) => {
  const productOrderId = row.productOrderId || this.ids[0];
  const orderCode = row.orderCode;
  const params = {queryParams: queryParams};
  // this.$tab.closeOpenPage(router.currentRoute);
  proxy?.$tab.openPage( '/mes/product-plan/index/' + productOrderId,"任务[" + orderCode + "]生产派工", params);
};

</script>
