<template>
  <el-drawer
    v-model="drawerVisible"
    :close-on-click-modal="false"
    :show-close="false"
    destroy-on-close
    direction="rtl"
    size="972px"
  >
    <template #header>
      <div class="drawerTitle">报工</div>
    </template>
    <template #default>
      <el-scrollbar>
        <div id="drawContent">
          <el-form
            ref="formRef"
            :disabled="formDisabled"
            label-position="left"
            label-width="auto"
            size="large"
          >
            <el-select
              v-if="processStore.scanInfo.batchReport == 1"
              v-model="selectedProcess"
              :filterable="true"
              multiple
              placeholder="请选择流转卡号，可以输入或者扫码筛选"
              style="margin-bottom: 20px"
            >
              <template #prefix
                ><img src="@/assets/icons/shaoma.svg"
              /></template>
              <el-option
                v-for="item in processList"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
            <el-row
              v-for="(per, index) in persons"
              :key="per.userName"
              :gutter="20"
              style="width: 100%"
            >
              <el-col :span="10">
                <el-form-item label="" prop="userName">
                  <el-select
                    v-model="per.userName"
                    filterable
                    placeholder="请选择人员"
                    value-key="id"
                  >
                    <el-option
                      v-for="item in dictStroe.allUsers"
                      :key="item.id"
                      :label="item.userName"
                      :value="item.userName"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="" prop="workingHoursRate">
                  <el-select
                    v-model="per.workingHoursRate"
                    placeholder="请选择工时比例"
                    value-key="value"
                  >
                    <el-option
                      v-for="item in rateArray"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <div v-if="!formDisabled" class="right-btns">
                  <CirclePlus
                    class="icon-btn"
                    @click="
                      persons.push({
                        userName: null,
                        workingHoursRate: null,
                      })
                    "
                  />
                  <Remove
                    v-if="index !== 0"
                    class="icon-btn"
                    @click="persons.splice(index, 1)"
                  />
                </div>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-scrollbar>
    </template>
    <template #footer>
      <div
        style="display: flex; margin-bottom: 10px"
        v-if="processStore.scanInfo.outTime == true"
      >
        <div style="margin-top:3px;font-size:18px;">超期原因: &nbsp;</div>

        <el-select
          v-model="outTimeReason"
          placeholder="Select"
          style="width: 240px"
        >
          <el-option
            v-for="item in dictStroe.dicts.out_time_reason"
            :key="item.value"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </div>
      <div class="bottom-btns">
        <el-button class="cancelBtn el-button-big" @click="cancelClick"
          >取消</el-button
        >
        <el-button
          v-if="!formDisabled"
          class="sureBtn el-button-big"
          type="primary"
          @click="confirmClick"
          >报工
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import { useProcessStore } from "@/store/modules/processView";
import { useDictionaryStore } from "@/store/modules/dictionary";
import { getProcessInfo, getunProcessedList } from "@/api/prosteps";
import { emitter, EventsNames } from "@/utils/common";
import { CirclePlus, Remove } from "@element-plus/icons-vue";
import { useUserStore } from "@/store/modules/user";
import { reportWork } from "@/api/process/reportBreak";

const processStore = useProcessStore();
const dictStroe = useDictionaryStore();
console.log(dictStroe.dicts.out_time_reason, "2");
const userStore = useUserStore();
// ================= 选择工序相关
const selectedProcess = ref<any[]>([]);
const processList = ref<any[]>([]);
const router = useRouter();

const drawerVisible = ref(false);
const formDisabled = ref(true);
const outTimeReason = ref(dictStroe.dicts.out_time_reason[0].dictValue);
const formRef = ref<InstanceType<typeof ElForm>>();

const persons = ref<
  {
    userName: string | null;
    workingHoursRate: number | null;
  }[]
>([{ userName: userStore.user.username ?? "", workingHoursRate: 100 }]);

const openReportWorkDrawer = () => {
  getProcessInfo(processStore.scanInfo.id).then((res) => {
    processStore.scanInfo.currentState = res.data.currentState;
    if (res.data.currentState !== "start") {
      ElMessage.warning("当前工单状态不允许报工");
      formDisabled.value = true;
      // reportWorkList(processStore.scanInfo.id).then((res) => {
      //   persons.value = res.data || [];
      // });
    } else {
      drawerVisible.value = true;
      formDisabled.value = false;
    }
    if (processStore.scanInfo.batchReport === 1) {
      getunProcessedList(processStore.scanInfo.id).then((res: any) => {
        processList.value = res.data ?? [];
      });
    }
  });
};

const cancelClick = () => {
  drawerVisible.value = false;
};

const confirmClick = () => {
  let total = 0;
  persons.value.forEach((item) => {
    total += item.workingHoursRate ?? 0;
  });
  if (total > 100) {
    ElMessage.error("总占比不能超过100%");
    return;
  }

  let params = {
    processId: processStore.scanInfo.id,
    processUserReportList: persons.value,
    seqList: selectedProcess.value,
    outTimeReason: outTimeReason.value,
  };

  reportWork(params).then((res: any) => {
    if (res.code === "200") {
      ElMessage.success("报工成功");
      emitter.emit(EventsNames.PROCESS_REDER);
      router.replace("/process");
      drawerVisible.value = false;
    } else {
      ElMessage.error("报工失败");
    }
  });
};

defineExpose({
  openReportWorkDrawer,
});

const rateArray: { label: string; value: number }[] = [
  { label: "10%", value: 10 },
  { label: "20%", value: 20 },
  { label: "30%", value: 30 },
  { label: "40%", value: 40 },
  { label: "50%", value: 50 },
  { label: "60%", value: 60 },
  { label: "70%", value: 70 },
  { label: "80%", value: 80 },
  { label: "90%", value: 90 },
  { label: "100%", value: 100 },
];
</script>

<style lang="scss" scoped>
#drawContent {
  width: 100%;
}

.right-btns {
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  padding-top: 7px;
  margin-bottom: 15px;

  .icon-btn {
    width: 30px;
    height: 30px;
  }
}

.bottom-btns {
  display: flex;
  justify-content: center;
  //margin-top: 20px;
  //margin-bottom: 20px;

  .button {
    margin-right: 20px;
  }

  .cancelBtn {
    width: 292px;
    height: 80px;
    background: rgba(0, 0, 0, 0.06);
    border-radius: 76px 76px 76px 76px;
  }

  .sureBtn {
    width: 292px;
    height: 80px;
    background: #0a59f7;
    border-radius: 76px 76px 76px 76px;
  }
}
</style>
