<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"
      @tree-load="treeLoad"
      @search-change="searchChange"
      @search-reset="resetChange"
      @size-change="dataList"
      @current-change="dataList"
      @selection-change="selectionChange"
      :span-method="spanMethod"
    >
      <template #orderCode="{ row }">
        <el-text v-if="row.orderCode">{{ row.orderCode }}</el-text>
        <div
          style="width: 100%; height: 100%; display: flex"
          v-if="!row.orderCode && row.operationDetails"
        >
          <div
            style="width: 120px; height: 100%"
            v-for="item in row.operationDetails"
          >
            <el-progress
              :text-inside="true"
              :stroke-width="35"
              :font-color="'#ff0000'"
              :percentage="(item.completeNum / row.workOrderNum) * 100"
              status="success"
              >{{ item.operationName }}(完成{{ item.completeNum }})
            </el-progress>
          </div>
        </div>
        <el-tag
          v-if="row.workOrderCode === '-' && row.stockNum > 0"
          type="primary"
          >库存数量:{{ row.stockNum }}</el-tag
        >
        <el-tag
          v-if="row.workOrderCode === '-' && row.stockNum === '0'"
          type="danger"
          >库存数量:{{ row.stockNum }}</el-tag
        >
        <el-tag v-if="row.workOrderCode === '-'" type="danger"
          >锁定数量:{{ row.freezeNum }}</el-tag
        >
      </template>
      <template #menu="{ size, row, index }">
        <el-button type="primary" link size="small" @click="handleEdit(row, 0)"
          ><i-ep-edit />{{
            row.materialState === "0"
              ? "发起准备"
              : row.materialState === "1"
                ? "编辑准备"
                : "详情"
          }}
        </el-button>
        <el-button
          type="primary"
          link
          v-if="row.materialState !== '2' && row.isFeedback === '0'"
          size="small"
          @click="feedBack(row, 0)"
          ><i-ep-select />缺料反馈
        </el-button>
        <!--        <el-button
                    type="primary"
                    link
                    v-if="row.deviceState === '0' || row.bom === '-' || row.craftFile === '-' || row.materialState === '0'"
                    size="small"
                    @click="handleRefresh(row.workOrderCode)"
                ><i-ep-edit />刷新
                </el-button>-->
      </template>
    </avue-crud>
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="80%"
      @close="dialog.visible = false"
    >
      <work-order-page queryType="1" @orderInfo="orderInfo" />
    </el-dialog>
    <el-dialog
      v-model="dialog1.visible"
      :title="dialog1.title"
      width="45%"
      @close="dialog1.visible = false"
    >
      <el-form ref="dataFormRef" :model="form" label-width="90px">
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="工单编码" prop="workOrderCode">
              <el-input v-model="form.workOrderCode" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单编码" prop="orderCode">
              <el-input v-model="form.orderCode" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单名称" prop="orderName">
              <el-input v-model="form.orderName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="物料编码" prop="materialCode">
              <el-input v-model="form.materialCode" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="物料名称" prop="materialName">
              <el-input v-model="form.materialName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="物料型号" prop="materialModel">
              <el-input v-model="form.materialModel" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="工单数量" prop="workOrderNum">
              <el-input v-model="form.workOrderNum" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" v-for="(item, index) in templates">
          <el-col :span="8">
            <el-form-item :label="templates[index].str">
              <el-switch
                @change="changeItem(templates[index])"
                class="mb-2"
                v-model="templates[index].state"
                style="
                  --el-switch-on-color: #13ce66;
                  --el-switch-off-color: #ff4949;
                "
                active-text="完成"
                inactive-text="未完成"
                :disabled="
                  form.materialState === '0' ||
                  (form.materialState === '1' &&
                    userStore.user.username !== templates[index].userName) ||
                  form.materialState === '2'
                "
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="准备人员">
              <el-select
                v-model="templates[index].userName"
                placeholder="准备人员"
                size="large"
                :disabled="
                  form.materialState === '1' || form.materialState === '2'
                "
                filterable
                style="width: 240px"
              >
                <el-option
                  v-for="item in userList"
                  :key="item.userName"
                  :label="item.userName"
                  :value="item.userName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="完成时间" v-if="templates[index].time">
              {{ templates[index].time }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            v-if="form.materialState !== '2'"
            @click="onSubmit"
            >{{ form.materialState === "0" ? "发起准备" : "提交" }}</el-button
          >
          <el-button @click="dialog1.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="dialog2.visible"
      :title="dialog2.title"
      width="45%"
      @close="dialog2.visible = false"
    >
      <el-form ref="formRef" :model="form" label-width="90px">
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="工单编码" prop="workOrderCode">
              <el-input v-model="form.workOrderCode" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单编码" prop="orderCode">
              <el-input v-model="form.orderCode" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单名称" prop="orderName">
              <el-input v-model="form.orderName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="物料编码" prop="materialCode">
              <el-input v-model="form.materialCode" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="物料名称" prop="materialName">
              <el-input v-model="form.materialName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="物料型号" prop="materialModel">
              <el-input v-model="form.materialModel" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="工单数量" prop="workOrderNum">
              <el-input v-model="form.workOrderNum" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="负责人" prop="manager">
              <el-select v-model="form.manager" placeholder="负责人" filterable>
                <el-option
                  v-for="item in userList"
                  :key="item.userName"
                  :label="item.userName"
                  :value="item.userName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报警接收人" prop="alarmManager">
              <el-select
                v-model="form.alarmManager"
                placeholder="报警接收人"
                filterable
              >
                <el-option
                  v-for="item in userList"
                  :key="item.userName"
                  :label="item.userName"
                  :value="item.userName"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-table :data="dataTable" :gutter="24">
          <el-table-column prop="materialCode" label="物料编码" width="180" />
          <el-table-column prop="materialName" label="物料名称" width="180" />
          <el-table-column prop="materialModel" label="规格" width="180" />
          <el-table-column prop="materialNum" label="数量" width="180">
            <template #default="{ scope, row }">
              <el-input-number
                v-model="row.materialNum"
                :precision="2"
                min="0.01"
                controls-position="right"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作">
            <template #default="scope">
              <el-button
                link
                type="danger"
                size="small"
                @click="delRow(scope.$index)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitData">确 定</el-button>
          <el-button @click="dialog2.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance } from "vue";
import { useCrud } from "@/hooks/userCrud";
import {
  addShortage,
  bomMaterial,
  prepareCheckInfo,
  refreshPrepareCheckInfo,
} from "@/api/order";
import { queryChildrenInfo } from "@/api/process";
import { useCommonStoreHook, useUserStore } from "@/store";
import { queryDictDataByType } from "@/api/system/dict";
import { getUserList } from "@/api/system/user";
import { ElMessage } from "element-plus";
const { isShowTable, tableType } = toRefs(useCommonStoreHook());
const router = useRouter();
const test = () => {
  isShowTable.value = true;
  tableType.value = tableType.value == 1 ? 2 : 1;
};
const userStore = useUserStore();
const dataTable = ref([]);
const feedBack = (row, index) => {
  dialog2.visible = true;
  form.value = row;
  queryUserList();
  bomMaterial(row.workOrderCode).then((data) => {
    dataTable.value = data.data;
  });
};
const dialog2 = reactive({
  title: "缺料反馈",
  visible: false,
});
const submitData = () => {
  form.value.itemList = dataTable.value;
  form.value.prepareId = form.value.id;
  addShortage(form.value).then((data) => {
    if (data.code === "200") {
      dialog2.visible = false;
      dataList();
      ElMessage.success("操作成功!");
    } else {
      ElMessage.error(data.message);
    }
  });
};
const userList = ref([]);
const templates = ref([]);
// 传入一个url，后面不带/
const { form, data, option, search, page, toDeleteIds, Methords, Utils } =
  useCrud({
    src: "/api/v1/plan/prepare",
  });
const { dataList, createRow, updateRow, deleteRow, searchChange, resetChange } =
  Methords; //增删改查
const { selectionChange, multipleDelete } = Methords; //选中和批量删除事件
const { checkBtnPerm, downloadTemplate, exportData } = Utils; //按钮权限等工具
const changeItem = (item) => {
  let time = "";
  if (item.state === "1") {
    let dateIn = new Date();
    let y = dateIn.getFullYear();
    let m = dateIn.getMonth() + 1;
    let d = dateIn.getDate();
    let h = dateIn.getHours();
    let mm = dateIn.getMinutes();
    let s = dateIn.getSeconds();
    time =
      y +
      (m < 10 ? "-0" : "-") +
      m +
      (d < 10 ? "-0" : "-") +
      d +
      " " +
      (h < 10 ? "0" : "") +
      h +
      (mm < 10 ? ":0" : ":") +
      mm +
      (s < 10 ? ":0" : ":") +
      s;
  }
  item.time = time;
};
const crudRef = ref(null); //crudRef.value 获取avue-crud对象
const dialog = reactive({
  title: "订单选择",
  visible: false,
});
const dialog1 = reactive({
  title: "生产准备",
  visible: false,
});
const onSubmit = (done, loading) => {
  form.value.materialStr = JSON.stringify(templates.value);
  if (form.value.materialState === "0") {
    form.value.materialState = "1";
  }
  updateRow(done, loading);
  dialog1.visible = false;
};
const merginState = ref(false);
const spanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (row.hasParent) {
    if (columnIndex === 6) {
      merginState.value = true;
      return [1, 11];
    } else if (columnIndex > 6 && merginState) {
      return [0, 0];
    }
  } else {
    merginState.value = false;
  }
  /*if (rowIndex % 2 === 0) {
    if (columnIndex === 0) {
      return [1, 2]
    } else if (columnIndex === 1) {
      return [0, 0]
    }
  }*/
};
const checkInfo = (code) => {
  prepareCheckInfo(code).then((data) => {
    form.value.deviceStr = data.data.deviceStr;
    form.value.deviceState = data.data.deviceState;
    form.value.materialState = data.data.materialState;
    form.value.materialStr = data.data.materialStr;
  });
};
const treeLoad = (tree, treeNode, resolve) => {
  queryChildrenInfo(tree.workOrderCode).then((data) => {
    resolve(data.data);
  });
};
const handleEdit = (row, index) => {
  dialog1.visible = true;
  form.value = row;
  templates.value = [];
  templates.value = JSON.parse(row.materialStr);
};
const handleRefresh = (code) => {
  refreshPrepareCheckInfo(code).then((data) => {
    if (data.code === "200") {
      ElMessage.success("刷新成功");
      dataList();
    } else {
      ElMessage.error(data.msg);
    }
  });
};
const orderInfo = (value) => {
  form.value.workOrderCode = value.workOrderCode;
  form.value.orderCode = value.orderCode;
  form.value.orderName = value.orderName;
  form.value.materialCode = value.materialCode;
  form.value.materialName = value.materialName;
  form.value.materialModel = value.materialModel;
  dialog.visible = false;
};
// 设置表格列或者其他自定义的option
option.value = Object.assign(option.value, {
  delBtn: false,
  selection: false,
  editBtn: false,
  tree: true,
  viewBtn: false,
  lazy: true,
  menuWidth: 180,
  rowKey: "workOrderCode",
  defaultExpandedKeys: [],
  addBtn: false,
  dialogWidth: "45%", // 设置编辑弹窗的宽度为50%
  column: [
    {
      label: "工单号",
      prop: "workOrderCode",
      search: true,
      minWidth: 120,
      editDisabled: true,
      rules: [
        {
          required: true,
          message: "工单号不能为空",
          trigger: "trigger",
        },
      ]/*,
      click: ({ value, column }) => {
        if (column.boxType) {
          dialog.visible = true;
        }
      },
      change: ({ value, column }) => {
        if (value) {
          checkInfo(value);
        }
      },*/
    },

    {
      label: "物料编码",
      prop: "materialCode",
      search: true,
      width: 130,
      overHidden: true,
      disabled: true,
      rules: [
        {
          required: true,
          message: "产品编码不能为空",
          trigger: "trigger",
        },
      ],
    },
    {
      label: "产品名称",
      prop: "materialName",
      disabled: true,
      width: 140,
      overHidden: true,
      search: true,
      rules: [
        {
          required: true,
          message: "产品名称不能为空",
          trigger: "trigger",
        },
      ],
    },
    {
      label: "产品规格",
      prop: "materialModel",
      disabled: true,
      search: true,
      width: 140,
      overHidden: true,
      rules: [
        {
          required: true,
          message: "产品规格不能为空",
          trigger: "trigger",
        },
      ],
    },
    {
      label: "数量",
      prop: "workOrderNum",
      disabled: true,
      width: 80,
      overHidden: true,
    },
    {
      label: "订单编号",
      prop: "orderCode",
      search: true,
      width: 130,
      overHidden: true,
      disabled: true,
      rules: [
        {
          required: true,
          message: "订单编号不能为空",
          trigger: "trigger",
        },
      ],
    },
    {
      label: "计划名称",
      prop: "orderName",
      search: true,
      disabled: true,
      width: 140,
      overHidden: true,
      rules: [
        {
          required: true,
          message: "计划名称不能为空",
          trigger: "trigger",
        },
      ],
    },
    /*{
      label: "文件资料",
      width: 350,
      overHidden: true,
      prop: "craftFile",
      addDisplay: false,
      viewDisplay: false,
      editDisplay: false,
      html: true,
      formatter: (val) => {
        if (val.craftFile !== '-') {
          return '<b class="el-tag el-tag--success el-tag--light">'+val.craftFile+'</b>';
        }
        return '<b class="el-tag el-tag--danger el-tag--light">-</b>';
      },
    },
    {
      label: "工艺BOM",
      width: 90,
      overHidden: true,
      prop: "bom",
      viewDisplay: false,
      addDisplay: false,
      editDisplay: false,
      html: true,
      formatter: (val) => {
        if (val.bom !== '-') {
          return '<b class="el-tag el-tag--success el-tag--light">'+val.bom+'</b>';
        }
        return '<b class="el-tag el-tag--danger el-tag--light">-</b>';
      },
    },
    {
      label: "工艺路线",
      width: 160,
      overHidden: true,
      viewDisplay: false,
      addDisplay: false,
      editDisplay: false,
      prop: "routeId",
      html: true,
      formatter: (val) => {
        if (val.routeId !== '-') {
          return '<b class="el-tag el-tag--success el-tag--light">'+val.routeId+'</b>';
        }
        return '<b class="el-tag el-tag--danger el-tag--light">-</b>';
      },
    },
    {
      label: "设备状况",
      prop: "deviceStr",
      disabled: true,
      width: 200,
      overHidden: true,
      html: true,
      formatter: (val) => {
        if (val.deviceState === '1') {
          return '<b class="el-tag el-tag--success el-tag--light">已齐套</b>';
        }
        return '<b class="el-tag el-tag--danger el-tag--light">'+val.deviceStr+'</b>';
      },
    },
    {
      label: "物料状态",
      prop: 'materialStr',
      disabled: true,
      width: 200,
      overHidden: true,
      span: 24,
      html: true,
      formatter: (val) => {
        if (val.materialState === '1') {
          return '<b class="el-tag el-tag--success el-tag--light">已齐套</b>';
        }
        return '<b class="el-tag el-tag--danger el-tag--light">'+val.materialStr+'</b>';
      },
    },*/
  ],
});
const queryUserList = () => {
  getUserList({}).then((data) => {
    userList.value = data.data;
  });
};
const delRow = (index) => {
  dataTable.value.splice(index, 1);
};
onMounted(() => {
  form.value.routeId = "1";
  form.value.materialState = 1;
  let url = window.location.href;
  if (url.includes("workOrderCode")) {
    search.value.workOrderCode = url.substring(
      url.indexOf("workOrderCode") + 14
    );
  }
  queryDictDataByType("prepare_template").then((res) => {
    if (res.data) {
      //templates.value = res.data
      res.data.forEach((item) => {
        option.value.column.push({
          label: item.dictLabel,
          prop: item.dictValue,
          width: 100,
          slot: true,
          display: false,
          html: true,
          formatter: (val) => {
            let state = "-1";
            if (val.materialStr) {
              let list = JSON.parse(val.materialStr);
              let obj = list.find((option) => option.name === item.dictValue);
              if (obj) {
                state = obj.state;
              }
            }
            if (state === "1") {
              return '<b class="el-tag el-tag--success el-tag--light">已完成</b>';
            } else if (state === "0") {
              return '<b class="el-tag el-tag--danger el-tag--light">未完成</b>';
            }
            return '<b class="el-tag el-tag--warrning el-tag--light">未配置</b>';
          },
        });
      });
    }
    option.value.column.push({
      label: "创建时间",
      prop: "created",
      width: 200,
      display: false,
    });
    option.value.column.push({
      label: "创建人",
      width: 200,
      prop: "creator",
      display: false,
    });
  });
  queryUserList();
  dataList();
});
</script>
<style scoped>
:deep(.el-progress-bar__innerText) {
  color: #737674;
  display: inline-block;
  font-size: 12px;
  margin: 0 5px;
  vertical-align: middle;
}
</style>
