<template>
  <div class="container2" id="shijian">
    <el-tabs v-model="activeName" type="card">
      <el-tab-pane label="待处理" name="no"/>
      <el-tab-pane label="审核完成" name="ok"/>
    </el-tabs>
    <div class="header">
      <Search
        :searchOptions="searchForm"
        :keepState="true"
        ref="searchRef"
        @dataList="getData"
      />
    </div>
    <div class="table">
      <el-button
        type="primary"
        size="small"
        class="btn"
        style="margin-bottom: 10px"
        @click="toAdd"
      >新增
      </el-button>
      <el-table :data="tableData" border>
        <el-table-column prop="formNo" label="编号"/>
        <el-table-column prop="materialModel" label="产品型号"/>
        <el-table-column prop="type" label="产品分类"/>
        <el-table-column prop="workOrderCode" label="生产批号"/>
        <el-table-column
          prop="seqs"
          label="管号"
          width="200"
          overhidden="true"
        />
        <el-table-column prop="seqNum" label="数量"/>
        <el-table-column prop="componentName" label="器件名称及型号"/>
        <el-table-column prop="num" label="数量"/>
        <el-table-column prop="company" label="供方单位" overhidden="true"/>
        <el-table-column
          prop="currentUserName"
          label="审核人"
          overhidden="true"
        />
        <el-table-column prop="auditType" label="审核类型">
          <template #default="{ row }">
            {{ getTextByAuditType(row.auditType) }}
          </template>
        </el-table-column>
        <el-table-column prop="state" label="审核状态">
          <template #default="{ row }">
            <div :style="{ color: getColorByState(row.state) }">
              {{ getTextByState(row.state) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="created" label="创建时间"/>
        <el-table-column
          align="center"
          width="160"
          prop=""
          label="操作"
          id="opear"
        >
          <template #default="{ row }">
            <el-button
              v-if="row.state === 0"
              link
              type="danger"
              @click="toDelete(row)"
            >删除
            </el-button>
            <el-button
              link
              v-if="
                (row.state === 0 || row.state === 1) &&
                row.currentUserName
                  ?.split(',')
                  .includes(userStore.user.username)
              "
              @click="handle(row)"
              type="primary"
            >处理
            </el-button>
            <el-button link @click="toDetail(row)" type="primary"
            >详情
            </el-button>
            <el-button
              link
              v-if="row.state === 3 && hasRemarkButtonPerm"
              @click="handleRemark(row)"
              type="primary"
            >备注
            </el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :total="currentOption.total"
        :page="currentOption.page"
        :limit="currentOption.limit"
        :pageSizes="currentOption.pageSizes"
        v-model:page="currentOption.page"
        v-model:limit="currentOption.limit"
        @pagination="getData"
      />
      <Add ref="addRef" @finish="getData"></Add>
      <Detail ref="detailRef"></Detail>
      <Handle20 ref="handle20Ref" @finish="getData"></Handle20>
      <Handle21 ref="handle21Ref" @finish="getData"></Handle21>
      <Handle2 ref="handle2Ref" @finish="getData"></Handle2>
      <Handle3 ref="handle3Ref" @finish="getData"></Handle3>
      <Handle4 ref="handle4Ref" @finish="getData"></Handle4>
      <Handle5 ref="handle5Ref" @finish="getData"></Handle5>
      <Handle6 ref="handle6Ref" @finish="getData"></Handle6>
      <Handle7 ref="handle7Ref" @finish="getData"></Handle7>
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="`备注 (${currentRow.materialModel || ''})`"
      width="40%"
    >
      <div class="remark-container">
        <div
          v-for="(remark, index) in remarks"
          :key="index"
          class="remark-item"
        >
          <el-input
            v-model="remark.content"
            type="textarea"
            :rows="3"
            placeholder="请输入备注内容"
            @change="updateRemark(index, remark.content)"
          />
          <div class="remark-actions">
            <div>
              <el-button
                type="danger"
                size="small"
                @click="removeRemark(index)"
                :icon="Delete"
                circle
              />
            </div>
            <div class="remark-info">
              <span class="remark-user">{{ remark.user }}</span>
              <span class="remark-time">{{ remark.time }}</span>
            </div>
          </div>
        </div>
        <el-button
          type="primary"
          @click="addRemark"
          class="add-btn"
          :icon="Plus"
        >新增备注
        </el-button
        >
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRemarkSubmit">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import Search from "@/components/Search/index.vue";
import {useSpcStore, useUserStore, useDictionaryStore} from "@/store";

const {dicts} = useDictionaryStore();
import {
  deleteFeedback,
  getUnqualifiedData,
  updateUnqualifiedData,
} from "@/api/unqualified/index";
import Add from "@/views/unqualified/add.vue";
import Detail from "@/views/unqualified/detail.vue";
import Handle20 from "@/views/unqualified/handle20.vue";
import Handle21 from "@/views/unqualified/handle21.vue";
import Handle2 from "@/views/unqualified/handle2.vue";
import Handle3 from "@/views/unqualified/handle3.vue";
import Handle4 from "@/views/unqualified/handle4.vue";
import Handle5 from "@/views/unqualified/handle5.vue";
import Handle6 from "@/views/unqualified/handle6.vue";
import Handle7 from "@/views/unqualified/handle7.vue";
import {Plus, Delete} from "@element-plus/icons-vue";

defineOptions({
  name: "SPCUnqualified",
});
const userStore = useUserStore();
const auditTypes = dicts.unqualified_audit_type;
const store = useSpcStore();

const router = useRouter();

const addRef = ref(null);

const currentOption = reactive({
  total: 0,
  page: 1,
  limit: 10,
});
const tableData = ref([]);
const searchRef = ref(null);
const searchForm = [
  {
    label: "编号",
    prop: "formNo",
    type: "input",
  },
  {
    label: "工单号",
    prop: "workOrderCode",
    type: "input",
  },
  {
    label: "供方单位",
    prop: "company",
    type: "input",
  },
  {
    label: "元器件名称及型号",
    prop: "componentName",
    type: "input",
  },
];

const getData = async (obj) => {
  const {data, code} = await getUnqualifiedData({
    ...searchRef.value.searchForm,
    pageNo: currentOption.page,
    pageSize: currentOption.limit,
  });
  if (code == "200") {
    tableData.value = data.records;
    currentOption.total = data.totalCount;
  }
};

const toAdd = () => {
  addRef.value && addRef.value.showDrawer();
};

const toDelete = async (row) => {
  const res = await deleteFeedback(row.id);
  currentOption.page = 1;
  getData();
  // const { code } = await deleteData({ id });
  // if (code == "200") {
  //   ElMessage.success("操作成功");
  //   getData();
  // }
};

// 处理相关
const handle20Ref = ref(null);
const handle21Ref = ref(null);
const handle2Ref = ref(null);
const handle3Ref = ref(null);
const handle4Ref = ref(null);
const handle5Ref = ref(null);
const handle6Ref = ref(null);
const handle7Ref = ref(null);
const handle = (row) => {
  if (row.remark2 && (!JSON.parse(row.remark2).content || JSON.parse(row.remark2).isSave)) {
    if (row.auditType == "1") {
      if (row.remark1 && !JSON.parse(row.remark1).user1) {
        handle2Ref.value && handle2Ref.value.showDrawer(row);
      } else {
        handle20Ref.value && handle20Ref.value.showDrawer(row); // 处理
      }
    } else {
      if (row.remark1 && !JSON.parse(row.remark1).user1) {
        handle2Ref.value && handle2Ref.value.showDrawer(row);
      } else {
        handle21Ref.value && handle21Ref.value.showDrawer(row); // 处理
      }
    }
  } else if (row.remark3 && !JSON.parse(row.remark3).content) {
    handle3Ref.value && handle3Ref.value.showDrawer(row); // 处理
  } else if (row.remark4 && !JSON.parse(row.remark4).content) {
    handle4Ref.value && handle4Ref.value.showDrawer(row); // 处理
  } else if (row.remark5 && !JSON.parse(row.remark5).content) {
    handle5Ref.value && handle5Ref.value.showDrawer(row); // 处理
  } else if (row.remark6 && !JSON.parse(row.remark6).content) {
    handle6Ref.value && handle6Ref.value.showDrawer(row); // 处理
  } else if (row.remark7 && !JSON.parse(row.remark7).content) {
    handle7Ref.value && handle7Ref.value.showDrawer(row); // 处理
  } else {
    ElMessage.info("该工单正在处理中。。。");
  }
};

// 详情
const detailRef = ref(null);
const toDetail = (row) => {
  getData();
  // 详情
  detailRef.value && detailRef.value.showDrawer(row);
};
const getTextByAuditType = (state) => {
  if (state) {
    const item = auditTypes.filter((v) => {
      console.log(
        "dictValue:" +
        v.dictValue +
        ",state:" +
        state +
        "..." +
        (v.dictValue === state)
      );
      return v.dictValue === state;
    });
    if (item.length > 0) {
      return item[0].dictLabel;
    }
  }
};
// 审核状态0待处理 1 审核中 2 审核驳回 3 审核完成
const getTextByState = (state) => {
  switch (state) {
    case 0:
      return "待处理";
    case 1:
      return "审核中";
    case 2:
      return "审核驳回";
    case 3:
      return "审核完成";
    default:
      return "";
  }
};
const getColorByState = (state) => {
  switch (state) {
    case 0:
      return "#59acbb";
    case 1:
      return "#bba559";
    case 2:
      return "#d96868";
    case 3:
      return "#67c23a";
    default:
      return "";
  }
};
const activeName = ref("no");

const dialogVisible = ref(false);
const currentRow = ref({});
const remarks = ref([]);

const handleRemark = (row) => {
  dialogVisible.value = true;
  currentRow.value = row;
  // 初始化备注数据
  try {
    remarks.value = row.remark8 ? JSON.parse(row.remark8) : [];
  } catch (e) {
    remarks.value = [];
  }
};

const formatNowTime = () => {
  const date = new Date();
  return (
    date.getFullYear() +
    "年" +
    (date.getMonth() + 1) +
    "月" +
    date.getDate() +
    "日"
  );
};

const addRemark = () => {
  remarks.value.push({
    content: "",
    time: formatNowTime(),
    user: userStore.user.username,
  });
};

const removeRemark = (index) => {
  remarks.value.splice(index, 1);
};

const updateRemark = (index, content) => {
  remarks.value[index].content = content;
  remarks.value[index].time = formatNowTime();
  remarks.value[index].user = userStore.user.username;
};

const handleRemarkSubmit = async () => {
  const validRemarks = remarks.value.filter((item) => item.content.trim());

  currentRow.value.remark8 = JSON.stringify(validRemarks);

  await updateUnqualifiedData(currentRow.value);

  ElMessage.success("备注保存成功");
  dialogVisible.value = false;
  getData();
};

const hasRemarkButtonPerm = computed(() => {
  console.log("permisson", userStore.user.perms);
  return userStore.user.perms?.some(
    (item) =>
      item.menuName === "备注" && // 按钮名称
      item.type === 2 && // 是否是按钮
      item.parentPath === "unqualified" //是否是不合格处置页面
  );
});

onMounted(() => {
  searchRef.value.searchForm.state = "0";
  getData();
});
watch(
  () => activeName.value,
  (val) => {
    if (val == "ok") {
      searchRef.value.searchForm.state = "1";
    } else {
      searchRef.value.searchForm.state = "0";
    }
    getData();
  }
);
</script>

<style scoped lang="scss">
.container2 {
  background-color: white;
  width: 100%;
  height: 100%;
  padding: 20px;
  display: flex;
  flex-direction: column;

  .header {
    width: 100%;
    height: auto;
  }

  .table {
    flex: 1;
    padding-bottom: 20px;
  }

  .formView {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;

    .formTitle {
      text-align: center;
      font-size: 20px;
      margin-bottom: 20px;
    }

    .formStyle {
      width: 400px;
    }
  }
}
</style>
<style lang="scss">
#shijian {
  .is-active {
    background-color: #f5f7fa;
  }
}

.remark-container {
  max-height: 60vh;
  overflow-y: auto;
  padding: 10px;

  .remark-item {
    margin-bottom: 15px;
    border-bottom: 1px dashed #eee;
    padding-bottom: 10px;

    .remark-actions {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 5px;

      .remark-info {
        display: flex;
        flex-direction: column;
        align-items: flex-end;

        .remark-user {
          font-size: 12px;
          color: #409eff;
          margin-bottom: 2px;
        }

        .remark-time {
          font-size: 12px;
          color: #999;
        }
      }
    }
  }

  .add-btn {
    margin-top: 10px;
  }
}
</style>
