<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-row :gutter="20">
              <el-col :span="10">
                <el-select
                  v-model="selectedSign"
                  :filterable="true"
                  placeholder="请选择签章名称"
                  style="margin-bottom: 20px"
                >
                  <el-option
                    v-for="item in signNameList"
                    :key="item.id"
                    :label="item.signatureName"
                    :value="item.id"
                  />
                </el-select>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-input
                  v-model="operateCondition"
                  placeholder="备注"
                  style="margin-bottom: 20px"
                  type="textarea"
                />
              </el-col>
            </el-row>

            <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" v-if="false">
                <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="10">
                <el-form-item label="" prop="selectedProcess">
                  <el-select
                    v-model="per.selectedProcess"
                    :filterable="true"
                    multiple
                    placeholder="请选择流转卡号，可以输入或者扫码筛选"
                    @remove-tag="removeSeq"
                    @visible-change="visibleSeq"
                    @focus="getUserName(index)"
                  >
                    <template #prefix
                      ><img src="@/assets/icons/shaoma.svg"
                    /></template>
                    <template #header>
                      <el-checkbox
                        v-model="per.checkAll"
                        @change="handleCheckAll(per)"
                      >
                        全选
                      </el-checkbox>
                    </template>
                    <el-option
                      v-for="item in process"
                      :key="item"
                      :label="item"
                      :value="item"
                    />
                  </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: 100,
                        selectedProcess: [],
                        checkAll: false,
                      })
                    "
                  />
                  <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 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, signList } from "@/api/process/reportBreak";

const processStore = useProcessStore();
const dictStroe = useDictionaryStore();
const userStore = useUserStore();

const router = useRouter();

const drawerVisible = ref(false);
const formDisabled = ref(true);

const signNameList = ref<any[]>([]);
const selectedSign = ref<any[]>([]);

const operateCondition = ref("");

const checkAll = ref(false);
const x = () => {};
const process = ref([]);
const visibleSeq = (val) => {
  if (val) {
    process.value = processList.value;
    if (persons.value && persons.value.length > 0) {
      let i=0;
      for (let element of persons.value) {
        if (element.selectedProcess && element.selectedProcess.length > 0) {
          //排除当前行的值
          if(currentUser.value&&currentUser.value!=i){
            for (let e of element.selectedProcess) {
              process.value = process.value.filter((item) => item !== e);
            }
          }

        }
        i++;
      }
    }
  }
};
const currentUser = ref(null);
const getUserName = (index) =>{
  currentUser.value=index;
  console.log(currentUser.value);
}
const handleCheckAll = (person) => {
  console.log("handleCheckAll", person);
  person.selectedProcess = [];
  if (person.checkAll) {
    person.selectedProcess = process.value;
  } else {
    person.selectedProcess = [];
  }
};

const formRef = ref<InstanceType<typeof ElForm>>();

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

const removeSeq = (item) => {
  console.log();
  selectedProcess.value = selectedProcess.value.filter((e) => e !== item);
};
const openReportWorkDrawer = () => {
  // 初始化数据
  selectedSign.value = [];
  operateCondition.value = "";
  persons.value = [
    {
      userName: userStore.user.username ?? "",
      workingHoursRate: 100,
      selectedProcess: [],
      checkAll: false,
    },
  ];
  processList.value = [];

  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;
    }
  });

  getunProcessedList(processStore.scanInfo.id).then((res: any) => {
    processList.value = res.data ?? [];
  });

  signList({ signatureType: "3" }).then((res) => {
    signNameList.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,
    signatureId: Array.isArray(selectedSign.value) && selectedSign.value.length === 0?null:selectedSign.value,
    operateCondition: operateCondition.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 },
];

// ================= 选择工序相关
const selectedProcess = ref<any[]>([]);
const processList = ref<any[]>([]);
</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>
