<template>
  <div class="tenant">
    <!-- <Banner /> -->
    <div class="content">
      <byTable :source="sourceList.data" :pagination="sourceList.pagination" :config="config" :loading="loading" highlight-current-row
               :selectConfig="selectConfig" :table-events="{
          //element talbe事件都能传
          select: select,
        }" :action-list="[]" @get-list="getList">
        <template #arrangedQuantity="{ item }">
          <div v-if="Number(item.productionQuantity) > item.arrangedQuantity" style="color: red; font-weight: 700">
            {{ item.arrangedQuantity }}
          </div>
          <div v-else>
            {{ item.arrangedQuantity }}
          </div>
        </template>

        <template #isCustomized="{ item }">
          <div>
            <span style="padding: 4px" :class="[item.isCustomized == 1 ? 'active' : '']">
              {{
                proxy.dictValueLabel(item.isCustomized, isCustomizedData)
              }}</span>
          </div>
        </template>

        <template #work="{ item }">
          <div style="width:100%">
            <span style="padding: 4px" :class="[item.researchStatus == 1 ? 'activea' : 'disActive']">
              【研】设计
            </span>
            <span style="padding: 4px;margin-left:8px" :class="[item.researchBomStatus == 1 ? 'activea' : 'disActive']">
              【研】BOM
            </span>
            <span style="padding: 4px;margin-left:8px" :class="[item.electricianBomStatus == 1 ? 'activea' : 'disActive']">
              【电】BOM
            </span>
            <span style="padding: 4px" :class="[item.technologyStatus == 1 ? 'activea' : 'disActive']">
              【制】工序
            </span>
            <span style="padding: 4px;margin-left:8px" :class="[item.bomStatus == 1 ? 'activea' : 'disActive']">
              【制】BOM
            </span>
            <span style="padding: 4px;margin-left:8px" :class="[item.productionQuantity ? 'activea' : 'disActive']">
              【制】下发
            </span>
          </div>
        </template>

        <template #completionRate="{ item }">
          <div style="width: 100%">
            <el-progress type="circle" :percentage="Number(item.completionRate)" width="60"
                         :status="Number(item.completionRate) == 100 ? 'success' : ''" />
          </div>
        </template>

        <template #btns="{ item }">
          <div style="width: 100%">
            <div v-if="props.isShowSelect">
              <el-button text type="primary" @click="handleSelectRow(item)">选择</el-button>
            </div>
            <div v-else>

              <!-- 研发 -->
              <span v-if="isYanFa">
                <el-button text type="primary" @click="handleUploadFile(item, false)" v-if="item.devUserId==userId">
                  <!-- {{
                    item.researchStatus ? "查看" : "上传"
                  }} -->
                  设计资料
                </el-button>
                <el-button text type="primary" v-if="item.devUserId==userId" @click="getDtl(item, item.researchBomStatus ? true : false,'all')">
                  <!-- {{ item.researchBomStatus ? "查看" : "调整" }} -->
                  BOM</el-button>
              </span>
              <!-- 电控 -->
              <span v-if="isDianGong">
                <el-button text type="primary" v-if="item.researchStatus && item.researchBomStatus"
                           @click="getDtl(item, item.electricianBomStatus ? true : false,2)">
                  <!-- {{ item.electricianBomStatus ? "查看" : "调整" }} -->
                  BOM</el-button>
              </span>

              <!-- 制图 -->
              <span v-if="isZhiTu && item.researchStatus && item.researchBomStatus">
                <span v-if="item.isCustomized == 1">
                  <el-button text type="primary" @click="getDtl(item, item.bomStatus ? true : false,1)">
                    <!-- {{ item.bomStatus ? "查看" : "调整" }} -->
                    BOM</el-button>
                </span>
                <span v-if="item.isCustomized == 1">
                  <el-button text type="primary" @click="
                      getDtlOne(item, item.technologyStatus ? true : false)
                    ">
                    <!-- {{
                      item.technologyStatus ? "查看" : "调整"
                    }} -->
                    工艺</el-button>
                </span>
                <span>
                  <el-button text type="primary" @click="handleUploadFile(item, true)">设计资料</el-button>
                </span>
                <span v-if="item.isCustomized == 0">
                  <span v-if="item.productionQuantity == null">
                    <el-button text type="primary" @click="handleOut(item)">下发</el-button>
                  </span>
                </span>
              </span>

              <span>
                <el-button text type="primary" @click="handlePrint(item)">打印</el-button>
              </span>

            </div>
          </div>
        </template>
      </byTable>
    </div>
    <!-- 研发调整bom -->

    <el-dialog :title="!isDetail ? '调整BOM' : '查看BOM'" v-model="dialogVisible" width="90%" v-loading="submitLoading" destroy-on-close>
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="byform">
        <template #slot>
          <div style="width: 100%;display:flex">
            <div style="padding-right:10px" v-if="submitType==1 || submitType=='all'" :style="{ width: submitType=='all'  ? '50%' : '100%' }">
              <div style="color: red; font-size: 14px">
                注意：这是单个产品的物料
              </div>
              <el-button type="primary" plain @click="clickSelect(1)">添加物料/半成品（五金）</el-button>
              <el-table :data="formData.data.workOrderBomList" style="margin-top:15px">
                <el-table-column prop="productCode" label="物料编码" />
                <el-table-column prop="productName" label="物料名称" />
                <el-table-column prop="productSpec" label="规格型号" />
                <el-table-column prop="productUnit" label="单位" :formatter="
                    (row) => dictValueLabel(row.productUnit, materialUnit)
                  " />
                <el-table-column prop="quantity" label="数量" width="150">
                  <template #default="{ row, $index }">
                    <el-form-item :prop="'workOrderBomList.' + $index + '.quantity'" :rules="rules.quantity" :inline-message="true">
                      <el-input-number v-model="row.quantity" :precision="2" :controls="false" :min="1" />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="zip" label="操作" width="100">
                  <template #default="{ $index }">
                    <el-button type="primary" link @click="handleRemove($index,1)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div style="padding-left:10px" v-if="submitType==2 || submitType=='all'" :style="{ width: submitType=='all'  ? '50%' : '100%' }">
              <div style="color: red; font-size: 14px">
                注意：这是单个产品的物料
              </div>
              <el-button type="primary" plain @click="clickSelect(2)">添加物料/半成品（电控）</el-button>
              <el-table :data="formData.data.workOrderBomListOne" style="margin-top:15px">
                <el-table-column prop="productCode" label="物料编码" />
                <el-table-column prop="productName" label="物料名称" />
                <el-table-column prop="productSpec" label="规格型号" />
                <el-table-column prop="productUnit" label="单位" :formatter="
                    (row) => dictValueLabel(row.productUnit, materialUnit)
                  " />
                <el-table-column prop="quantity" label="数量" width="150">
                  <template #default="{ row, $index }">
                    <el-form-item :prop="'workOrderBomListOne.' + $index + '.quantity'" :rules="rules.quantity" :inline-message="true">
                      <el-input-number v-model="row.quantity" :precision="2" :controls="false" :min="1" />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="zip" label="操作" width="100">
                  <template #default="{ $index }">
                    <el-button type="primary" link @click="handleRemove($index,2)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitForm(0)" size="large" :loading="submitLoading">
          保 存
        </el-button>
        <el-button type="primary" @click="submitForm(1)" size="large" :loading="submitLoading" v-if="!isDetail">
          提 交
        </el-button>
      </template>
    </el-dialog>

    <el-dialog :title="!isDetailOne ? '调整工艺' : '查看工艺'" v-model="dialogVisibleOne" width="90%" v-loading="loadingOne" destroy-on-close>
      <byForm :formConfig="formConfigOne" :formOption="formOptionOne" v-model="formData.dataOne" :rules="rulesOne" ref="byformOne">
        <template #lineSlot>
          <div class="processChart" style="width:100%">
            <div class="from">
              <div class="commons-title">工序</div>
              <!-- <div>
                <el-form labelPosition='top'>
                  <el-form-item label="工序" label-width="80px">
                  </el-form-item>
                </el-form>
              </div> -->
            </div>
            <div class="content">
              <div class="commons-title">工艺路线</div>
              <div class="chart-warp">
                <vueFlow :nodeObject="nodeObject" ref="vueFlowDom" @addRow="clickAdd" @changeName="changeName" @removeRow="removeRow"></vueFlow>
              </div>
            </div>
          </div>

        </template>

        <template #slot>
          <div style="width: 100%" class="tableDrop">
            <!-- <el-button type="primary" plain @click="clickAdd">添加工序</el-button> -->
            <el-table :data="formData.dataOne.workOrderProductionProcessesList" style="width: 100%; margin-top: 16px" row-key="id">
              <el-table-column label="工序名称" width="150">
                <template #default="{ row, $index }">
                  <div style="width: 100%">
                    <el-form-item :prop="
                        'workOrderProductionProcessesList.' + $index + '.name'
                      " :rules="rulesOne.name" :inline-message="true">
                      <el-input v-model="row.name" placeholder="请输入" disabled />
                    </el-form-item>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="工艺说明" width="300">
                <template #default="{ row, $index }">
                  <div style="width: 100%">
                    <el-form-item :prop="
                        'workOrderProductionProcessesList.' +
                        $index +
                        '.remarks'
                      " :rules="rulesOne.remarks" :inline-message="true">
                      <el-input v-model="row.remarks" type="textarea" placeholder="请输入" />
                    </el-form-item>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="图纸">
                <template #default="{ row, $index }">
                  <div style="width: 100%">
                    <el-form-item :prop="
                        'workOrderProductionProcessesList.' + $index + '.name'
                      " :rules="rulesOne.name" :inline-message="true">
                      <el-upload v-model:fileList="row.fileList" :show-file-list="false" class="upload-demo"
                                 action="https://winfaster.obs.cn-south-1.myhuaweicloud.com" :data="uploadData" :before-upload="
                          (file) => handleBeforeUpload(file, $index)
                        ">
                        <el-icon :size="17" style="margin-top: 12px; cursor: pointer">
                          <Plus />
                        </el-icon>
                      </el-upload>

                      <div v-if="row.fileListCopy && row.fileListCopy.length > 0">
                        <el-tag style="margin-left: 10px" class="ml-2" type="info" v-for="(item, index) in row.fileListCopy"
                                :key="index">{{ item.fileName }}</el-tag>
                      </div>
                    </el-form-item>
                  </div>
                </template>
              </el-table-column>

              <!-- <el-table-column align="center" label="操作" width="60" fixed="right">
                <template #default="{ $index }">
                  <el-button type="primary" link @click="clickDelete($index)">删除</el-button>
                </template>
              </el-table-column> -->
            </el-table>
          </div>
        </template>
        <template #file>
          <div style="width: 100%">
            <el-upload v-model:fileList="formData.dataOne.fileList" action="https://winfaster.obs.cn-south-1.myhuaweicloud.com" :data="uploadData"
                       multiple :before-upload="handleBeforeUploadOne" :on-success="handleSuccess" :on-preview="onPreviewFile">
              <el-button type="primary" plain>选择</el-button>
            </el-upload>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="dialogVisibleOne = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitFormOne(0)" size="large" :loading="loadingOne" v-if="!isDetailOne">
          保 存
        </el-button>
        <el-button type="primary" @click="submitFormOne(1)" size="large" :loading="loadingOne" v-if="!isDetailOne">
          提 交
        </el-button>
      </template>
    </el-dialog>

    <el-dialog :title="'工单下发'" v-model="dialogVisibleTwo" width="500" v-loading="submitLoading" destroy-on-close>
      <byForm :formConfig="formConfigTwo" :formOption="formOptionTwo" v-model="formData.dataTwo" :rules="rulesTwo" ref="byformTwo">
      </byForm>
      <template #footer>
        <el-button @click="dialogVisibleTwo = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitFormTwo()" size="large" :loading="submitLoading">
          提 交
        </el-button>
      </template>
    </el-dialog>

    <el-dialog :title="'上传设计资料'" v-model="informationDialog" width="500" v-loading="submitLoading" destroy-on-close>
      <byForm :formConfig="informationFormConfig" :formOption="informationFormOption" v-model="formData.dataThree">
        <template #file>
          <div style="width: 100%">
            <el-upload v-model:fileList="formData.dataThree.fileList" action="https://winfaster.obs.cn-south-1.myhuaweicloud.com" :data="uploadData"
                       multiple :before-upload="handleBeforeUploadOne" :on-success="handleSuccess" :on-preview="onPreviewFile">
              <el-button>选择</el-button>
            </el-upload>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="informationDialog = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitInformationForm(0)" size="large" :loading="submitLoading" v-if="!showUploadSubmitOne">
          保 存
        </el-button>
        <el-button type="primary" @click="submitInformationForm(1)" size="large" :loading="submitLoading"
                   v-if="!showUploadSubmitOne && !showUploadSubmit">
          提 交
        </el-button>
      </template>
    </el-dialog>

    <el-dialog title="打印产品需求单" v-if="printDialog" v-model="printDialog" width="680">
      <ProductDemandPDF :rowData="rowData"></ProductDemandPDF>

      <template #footer>
        <el-button @click="printDialog = false" size="large">取 消</el-button>
        <el-button type="primary" v-print="printObj" size="large">打 印</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="openMaterial" title="选择物料/半成品" width="70%" append-to-body>
      <SelectMaterial @handleSelect="handleSelect"></SelectMaterial>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="openMaterial = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
  
<script setup>
/* eslint-disable vue/no-unused-components */
import { ElMessage, ElMessageBox } from "element-plus";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import { computed, defineComponent, nextTick, ref } from "vue";
import useUserStore from "@/store/modules/user";
import SelectMaterial from "@/components/product/SelectMaterial";
import Sortable from "sortablejs";
import ProductDemandPDF from "@/components/PDF/productDemandPDF.vue";
import vueFlow from "@/views/JXSK/production/processConfig/vueFlow.vue";

const userInfo = useUserStore();
const userId = computed(() => userInfo.user.userId);
const props = defineProps({
  isShowSelect: {
    type: Boolean,
    default: false,
  },
});
const uploadData = ref({});
let fileList = ref([]);
let fileListCopy = ref([]);
const loading = ref(false);
const submitLoading = ref(false);
const loadingOne = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
  },
});
let dialogVisible = ref(false);
let dialogVisibleOne = ref(false);
let openMaterial = ref(false);
let roomDialogVisible = ref(false);
let modalType = ref("add");
let rules = ref({
  quantity: [{ required: true, message: "请输入数量", trigger: "blur" }],
});
let rulesOne = ref({
  name: [{ required: true, message: "请输入工序名称", trigger: "blur" }],
  remarks: [{ required: true, message: "请输入工艺说明", trigger: "blur" }],
});
let rulesTwo = ref({
  stockWaitQuantity: [
    { required: true, message: "请输入出库数量", trigger: "blur" },
  ],
  productionQuantity: [
    { required: true, message: "请输入生产数量", trigger: "blur" },
  ],
});
const { proxy } = getCurrentInstance();
const materialUnit = ref([]);
const workOrderSource = ref([]);
const isCustomizedData = ref([
  {
    label: "是",
    value: "1",
  },
  {
    label: "否",
    value: "0",
  },
]);
const isComplete = ref([
  {
    label: "已处理",
    value: "1",
  },
  {
    label: "未处理",
    value: "0",
  },
]);
const selectConfig = computed(() => [
  // {
  //   label: "工单来源",
  //   prop: "source",
  //   data: workOrderSource.value,
  // },
  {
    label: "是否定制",
    prop: "isCustomized",
    data: isCustomizedData.value,
  },
  {
    label: "处理状态",
    prop: "isComplete",
    data: isComplete.value,
  },
]);

const config = computed(() => {
  return [
    // {
    //   attrs: {
    //     label: "工单来源",
    //     prop: "source",
    //     width: 100,
    //   },
    //   render(source) {
    //     return proxy.dictValueLabel(source, workOrderSource.value);
    //   },
    // },
    {
      attrs: {
        label: "销售单号",
        prop: "contractCode",
        width: 110,
      },
    },
    {
      attrs: {
        label: "合同创建时间",
        prop: "contractCreateTime",
        width: 160,
      },
    },
    {
      attrs: {
        label: "工单单号",
        prop: "code",
        width: 110,
      },
    },
    {
      attrs: {
        label: "产品名称",
        prop: "productName",
        "min-width": 220,
      },
    },
    {
      attrs: {
        label: "产品型号",
        prop: "productSpec",
        width: 100,
      },
    },
    {
      attrs: {
        label: "是否定制",
        slot: "isCustomized",
        width: 80,
      },
      // render(isCustomized) {
      //   return isCustomized == 1 ? "是" : "否";
      // },
    },
    {
      attrs: {
        label: "工单数量",
        prop: "quantity",
        width: 100,
      },
    },
    {
      attrs: {
        label: "计划出库数量",
        prop: "stockWaitQuantity",
        width: 120,
      },
    },
    {
      attrs: {
        label: "计划生产数量",
        prop: "productionQuantity",
        width: 120,
      },
    },
    {
      attrs: {
        type: "slot",
        label: "已计划数量",
        slot: "arrangedQuantity",
        width: 120,
      },
    },
    {
      attrs: {
        type: "slot",
        label: "工作",
        slot: "work",
        width: 300,
        fixed: "right",
      },
    },
    {
      attrs: {
        label: "完成率",
        slot: "completionRate",
        width: 120,
        align: "center",
        fixed: "right",
      },
      // render(completionRate) {
      //   if (completionRate !== undefined && completionRate !== "") {
      //     return completionRate + "%";
      //   }
      // },
    },

    {
      attrs: {
        label: "操作",
        slot: "btns",
        width: "220",
        align: "center",
        fixed: "right",
      },
    },
  ];
});

let formData = reactive({
  data: {},
  dataOne: {},
  dataTwo: {},
  treeData: [],
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
  disabled: false,
});
const formOptionOne = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
  disabled: false,
});
const formOptionTwo = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
  disabled: false,
});
const informationFormOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
  disabled: false,
});

const byform = ref(null);
const byformOne = ref(null);

const treeData = ref([]);
const formConfig = reactive([
  {
    type: "slot",
    slotName: "slot",
  },
]);
const formConfigOne = reactive([
  {
    type: "slot",
    slotName: "lineSlot",
    label: "",
  },
  {
    type: "slot",
    slotName: "slot",
    label: "",
  },
  {
    type: "slot",
    slotName: "file",
    label: "上传附件",
  },
]);
const formConfigTwo = reactive([
  {
    type: "input",
    label: "产品名称",
    prop: "productName",
    disabled: true,
  },
  {
    type: "input",
    label: "工单数量",
    prop: "orderQuantity",
    disabled: true,
    itemWidth: 51,
  },
  {
    type: "input",
    label: "库存数量",
    prop: "availableStockQuantity",
    disabled: true,
    itemWidth: 51,
  },
  {
    type: "number",
    prop: "stockWaitQuantity",
    label: "出库数量",
    itemWidth: 51,
    precision: 0,
    min: 0,
    controls: false,
    style: {
      width: "100%",
    },
  },
  {
    type: "number",
    prop: "productionQuantity",
    label: "生产数量",
    itemWidth: 51,
    precision: 0,
    min: 0,
    controls: false,
    style: {
      width: "100%",
    },
  },
]);
const informationFormConfig = reactive([
  {
    type: "slot",
    slotName: "file",
    label: "上传设计资料",
  },
]);
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/workOrder/pageByJxst", sourceList.value.pagination)
    .then((message) => {
      sourceList.value.data = message.rows;
      sourceList.value.pagination.total = message.total;
      setTimeout(() => {
        loading.value = false;
      }, 200);
    });
};
const openModal = () => {
  dialogVisible.value = true;
  modalType.value = "add";
  formData.data = {};
};

const submitForm = (flag) => {
  byform.value.handleSubmit((valid) => {
    let type = "";
    if (submitType.value == 1) {
      type = 1;
    } else if (submitType.value == 2) {
      type = 2;
    }
    formData.data.type = type;
    if (flag == 1) {
      ElMessageBox.confirm(`你确定提交吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        submitLoading.value = true;
        if (submitType.value == 1) {
          formData.data.bomStatus = 1;
        } else if (submitType.value == 2) {
          formData.data.electricianBomStatus = 1;
        } else {
          formData.data.researchBomStatus = 1;
        }
        const arr = [
          ...formData.data.workOrderBomList,
          ...formData.data.workOrderBomListOne,
        ];
        // formData.data.workOrderBomList = arr;
        proxy
          .post("/workOrder/editBom", {
            ...formData.data,
            workOrderBomList: arr,
          })
          .then(
            (res) => {
              ElMessage({
                message: "操作成功",
                type: "success",
              });
              dialogVisible.value = false;
              submitLoading.value = false;
              getList();
            },
            (err) => (submitLoading.value = false)
          );
      });
    } else {
      submitLoading.value = true;
      const arr = [
        ...formData.data.workOrderBomList,
        ...formData.data.workOrderBomListOne,
      ];
      // formData.data.workOrderBomList = arr;
      proxy
        .post("/workOrder/editBom", { ...formData.data, workOrderBomList: arr })
        .then(
          (res) => {
            ElMessage({
              message: "操作成功",
              type: "success",
            });
            dialogVisible.value = false;
            submitLoading.value = false;
            getList();
          },
          (err) => (submitLoading.value = false)
        );
    }
  });
};
const vueFlowDom = ref(null);

const submitApi = (type) => {
  const data = vueFlowDom.value.submitAll();
  if (!data) {
    return;
  }
  formData.dataOne.customizedNodeObject = data.nodeObject;
  formData.dataOne.fileList = formData.dataOne.fileList.map((item) => {
    return {
      id: item.raw.id,
      fileName: item.raw.fileName,
      fileUrl: item.raw.fileUrl,
      uploadState: item.raw.uploadState,
    };
  });

  for (
    let i = 0;
    i < formData.dataOne.workOrderProductionProcessesList.length;
    i++
  ) {
    const e = formData.dataOne.workOrderProductionProcessesList[i];
    e.fileList = e.fileListCopy;
  }
  formData.dataOne.technologyStatus = type;
  loadingOne.value = true;
  proxy.post("/workOrderProductionProcesses/edit", formData.dataOne).then(
    (res) => {
      ElMessage({
        message: "操作成功",
        type: "success",
      });
      dialogVisibleOne.value = false;
      loadingOne.value = false;
      getList();
    },
    (err) => (loadingOne.value = false)
  );
};
const submitFormOne = (type) => {
  byformOne.value.handleSubmit((valid) => {
    // for (
    //   let i = 0;
    //   i < formData.dataOne.workOrderProductionProcessesList.length;
    //   i++
    // ) {
    //   const e = formData.dataOne.workOrderProductionProcessesList[i];
    //   if (!e.fileListCopy.length > 0) {
    //     return ElMessage({
    //       message: "请上传图纸",
    //       type: "info",
    //     });
    //   }
    // }
    if (type) {
      ElMessageBox.confirm(`你确定提交吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        submitApi(type);
      });
    } else {
      submitApi(type);
    }
  });
};
const isDetail = ref(false);
const submitType = ref("all");
const getDtl = (row, flag, submit) => {
  submitType.value = submit;
  isDetail.value = flag;
  modalType.value = "edit";
  proxy.post("/workOrderBom/list", { workOrderId: row.id }).then((res) => {
    // 五金
    let workOrderBomList = res.filter((x) => x.type == 1);
    let workOrderBomListOne = res.filter((x) => x.type == 2);
    formData.data = {
      workOrderBomList: workOrderBomList || [],
      workOrderBomListOne: workOrderBomListOne || [],
      workOrderId: row.id,
    };
    dialogVisible.value = true;
  });
};

const handleRemove = (index, type) => {
  if (type == 1) {
    formData.data.workOrderBomList.splice(index, 1);
  } else {
    formData.data.workOrderBomListOne.splice(index, 1);
  }
};
// 对el-table进行拖拽排序
const initSort = () => {
  const tbody = document.querySelector(
    ".tableDrop .el-table__body-wrapper tbody"
  );
  Sortable.create(tbody, {
    onEnd({ newIndex, oldIndex }) {
      if (newIndex == oldIndex) return;
      formData.dataOne.workOrderProductionProcessesList.splice(
        newIndex,
        0,
        formData.dataOne.workOrderProductionProcessesList.splice(oldIndex, 1)[0]
      );
      var newArray = formData.dataOne.workOrderProductionProcessesList.slice(0);
      formData.dataOne.workOrderProductionProcessesList = [];
      nextTick(() => {
        formData.dataOne.workOrderProductionProcessesList = newArray;
      });
    },
  });
};
const isDetailOne = ref(false);
const nodeObject = ref("");

const getDtlOne = (row, flag) => {
  isDetailOne.value = flag;
  // formOptionOne.disabled = flag;
  formOptionOne.disabled = false;

  modalType.value = "edit";
  proxy
    .post("/workOrderProductionProcesses/detail", { workOrderId: row.id })
    .then((res) => {
      nodeObject.value = res.customizedNodeObject;
      dialogVisibleOne.value = true;
      res.workOrderProductionProcessesList =
        res.workOrderProductionProcessesList.map((x) => {
          if (x.fileList && x.fileList.length > 0) {
            x.fileListCopy = x.fileList.map((x) => ({ ...x }));
          } else {
            x.fileList = [];
          }
          return x;
        });
      formData.dataOne = {
        workOrderId: row.id,
        workOrderProductionProcessesList: res.workOrderProductionProcessesList,
        fileList: [],
      };
      // nextTick(() => {
      //   initSort();
      // });
      proxy
        .post("/fileInfo/getList", { businessIdList: [row.id], fileType: 1 })
        .then((fileObj) => {
          if (fileObj[row.id] && fileObj[row.id].length > 0) {
            formData.dataOne.fileList = fileObj[row.id].map((item) => {
              return {
                raw: item,
                name: item.fileName,
                url: item.fileUrl,
              };
            });
          }
        });
    });
};

const getDict = () => {
  proxy.getDictOne(["material_unit", "work_order_source"]).then((res) => {
    materialUnit.value = res["material_unit"].map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
    workOrderSource.value = res["work_order_source"].map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
  });
};
const isYanFa = ref(false);
const isZhiTu = ref(false);
const isDianGong = ref(false);

const checkShow = () => {
  // 当前账号角色是否是研发
  if (userInfo.roles.includes("dev")) {
    isYanFa.value = true;
  }
  // 当前角色是否是制图
  if (userInfo.roles.includes("design")) {
    isZhiTu.value = true;
  }
  // 当前角色是否是电工
  if (userInfo.roles.includes("electrician")) {
    isDianGong.value = true;
  }
};
checkShow();
getList();
getDict();
const selectType = ref(-1);
const clickSelect = (type) => {
  selectType.value = type;
  openMaterial.value = true;
};

const handleSelect = (row) => {
  if (selectType.value == 1) {
    const flag = formData.data.workOrderBomList.some(
      (x) => x.productId === row.id
    );
    if (flag)
      return ElMessage({
        message: "该物料已选择",
        type: "info",
      });
    formData.data.workOrderBomList.push({
      productId: row.id,
      productCode: row.code,
      productName: row.name,
      productSpec: row.spec,
      productUnit: row.unit,
      quantity: null,
      type: "1",
    });
  } else {
    const flag = formData.data.workOrderBomListOne.some(
      (x) => x.productId === row.id
    );
    if (flag)
      return ElMessage({
        message: "该物料已选择",
        type: "info",
      });
    formData.data.workOrderBomListOne.push({
      productId: row.id,
      productCode: row.code,
      productName: row.name,
      productSpec: row.spec,
      productUnit: row.unit,
      quantity: null,
      type: "2",
    });
  }
  return ElMessage({
    message: "选择成功",
    type: "success",
  });
};

const clickAdd = ({ productionId, name }) => {
  let obj = {
    fileList: [],
    fileListCopy: [],
    name: "",
    remarks: "",
  };
  if (productionId) {
    obj.id = productionId;
  }
  if (name) {
    obj.name = name;
  }
  formData.dataOne.workOrderProductionProcessesList.push(obj);
};

const removeRow = ({ id }) => {
  const index = formData.dataOne.workOrderProductionProcessesList.findIndex(
    (x) => x.id == id
  );
  if (index > -1) {
    formData.dataOne.workOrderProductionProcessesList.splice(index, 1);
  }
};

const changeName = ({ productionId, name }) => {
  const index = formData.dataOne.workOrderProductionProcessesList.findIndex(
    (x) => x.id == productionId
  );
  if (index > -1) {
    formData.dataOne.workOrderProductionProcessesList[index].name = name;
  }
};
const clickDelete = (index) => {
  formData.dataOne.workOrderProductionProcessesList.splice(index, 1);
};

const handleBeforeUpload = async (file, index) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  uploadData.value = res.uploadBody;
  formData.dataOne.workOrderProductionProcessesList[index].fileListCopy = [
    {
      id: res.id,
      fileName: res.fileName,
      path: res.fileUrl,
      url: res.fileUrl,
      uid: file.uid,
    },
  ];
};

const handleBeforeUploadOne = async (file) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  uploadData.value = res.uploadBody;
  file.id = res.id;
  file.fileName = res.fileName;
  file.fileUrl = res.fileUrl;
  file.uploadState = true;
  return true;
};
const handleSuccess = (any, UploadFile) => {
  UploadFile.raw.uploadState = false;
};
const onPreviewFile = (file) => {
  window.open(file.raw.fileUrl, "_blank");
};
const dialogVisibleTwo = ref(false);
const byformTwo = ref(null);
const handleOut = (row) => {
  dialogVisibleTwo.value = true;
  proxy.post("/workOrder/detail", { id: row.id }).then((res) => {
    formData.dataTwo = {
      id: row.id,
      productName: row.productName + `（${row.productSpec}）`,
      orderQuantity: row.quantity,
      productionQuantity: res.productionQuantity
        ? res.productionQuantity
        : null,
      availableStockQuantity: res.availableStockQuantity,
    };
  });
};

const submitFormTwo = (type) => {
  byformTwo.value.handleSubmit((valid) => {
    if (
      formData.dataTwo.productionQuantity +
        formData.dataTwo.stockWaitQuantity !=
      Number(formData.dataTwo.orderQuantity)
    ) {
      return ElMessage({
        message: "出库数量和生产数量合必须等于工单数量",
        type: "info",
      });
    }
    if (
      formData.dataTwo.stockWaitQuantity >
      Number(formData.dataTwo.availableStockQuantity)
    ) {
      return ElMessage({
        message: "出库数量不可大于库存数量",
        type: "info",
      });
    }
    submitLoading.value = true;
    proxy.post("/workOrder/distribute", formData.dataTwo).then(
      (res) => {
        ElMessage({
          message: "操作成功",
          type: "success",
        });
        dialogVisibleTwo.value = false;
        submitLoading.value = false;
        getList();
      },
      (err) => (submitLoading.value = false)
    );
  });
};
const informationDialog = ref(false);
const showUploadSubmit = ref(false);
const showUploadSubmitOne = ref(false);

const handleUploadFile = (row, flag) => {
  showUploadSubmit.value = row.researchStatus == 1 ? true : false;
  showUploadSubmitOne.value = flag;
  formData.dataThree = {
    id: row.id,
    fileList: [],
  };
  informationDialog.value = true;
  proxy
    .post("/fileInfo/getList", {
      businessIdList: [row.id],
      fileType: 0,
    })
    .then((res) => {
      if (res[row.id] && res[row.id].length > 0) {
        formData.dataThree.fileList = res[row.id].map((item) => {
          return {
            raw: item,
            name: item.fileName,
            url: item.fileUrl,
          };
        });
      }
    });
};
const submitInformationForm = (type) => {
  if (formData.dataThree.fileList && formData.dataThree.fileList.length > 0) {
    formData.dataThree.fileList = formData.dataThree.fileList.map((x) => x.raw);
    formData.dataThree.researchStatus = type == 1 ? "1" : "";
    submitLoading.value = true;
    proxy.post("/workOrder/research", formData.dataThree).then(
      (res) => {
        ElMessage({
          message: "操作成功",
          type: "success",
        });
        informationDialog.value = false;
        submitLoading.value = false;
        getList();
      },
      (err) => (submitLoading.value = false)
    );
  } else {
    return ElMessage({
      message: "请上传设计资料",
      type: "info",
    });
  }
};
const printDialog = ref(false);
const rowData = ref({});
const handlePrint = (row) => {
  rowData.value = {
    id: row.id,
  };
  printDialog.value = true;
};
const printObj = ref({
  id: "pdfDom",
  popTitle: "",
  extraCss:
    "https://cdn.bootcdn.net/ajax/libs/animate.css/4.1.1/animate.compat.css, https://cdn.bootcdn.net/ajax/libs/hover.css/2.3.1/css/hover-min.css",
  extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>',
});

const handleSelectRow = (row) => {
  proxy.$emit("handleSelectRow", row);
};
</script>
  
<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
::v-deep(.el-progress__text) {
  font-size: 15px !important;
}

.active {
  background: #98db6b;
  color: #fff;
  border-radius: 4px;
}

.activea {
  background: #98db6b;
  color: #fff;
  border-radius: 4px;
  border: 1px solid #98db6b;
}
.disActive {
  // background: #fa9841;
  // background: #c4c4c4;
  // border: 1px solid #1c1b1b;
  border-radius: 4px;
  // color: #1c1b1b;
  border: 1px solid #c4c4c4;
  color: #c4c4c4;
}

.processChart {
  border: 1px solid #ccc;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  position: relative;
  .from {
    width: 400px;
    background: #fff;
    border-radius: 5px;
    padding: 20px;
  }
  .content {
    width: calc(100% - 420px);
    border-radius: 5px;
    padding: 20px;
    background: #fff;
  }
}
.chart-warp {
  width: 100%;
  // height: calc(100vh - 280px);
}
</style>