<template>
  <div>
    <el-drawer v-model="drawerVisible" size="800" :close-on-click-modal="false">
      <template #header>
        <h4>新增不合格审理</h4>
      </template>
      <template #default>
        <el-form
          ref="baseInfoRef"
          :model="saleForm"
          label-width="120"
          :rules="rules"
          style="max-width: 600px"
        >
          <el-form-item label="生产批号">
            <el-select
              v-model="selectOrderCode"
              value-key="workOrderCode"
              placeholder="请输入关键词搜索批号"
              style="width: 100%"
              filterable
              remote
              :remote-method="remoteOrderSearch"
              :loading="orderLoading"
              clearable
              @change="orderSelect"
            >

              <el-option
                v-for="item in orders"
                :key="item.workOrderCode"
                :label="item.workOrderCode"
                :value="item"
              />
            </el-select>
            <!--            :label="item.orderName + `(批号: ${item.workOrderCode})`"-->

          </el-form-item>
          <!--
          <el-form-item label="检验批号" hidden>
            <div>{{ selectedOrder.workOrderCode }}</div>
          </el-form-item>-->
          <el-form-item label="产品编号" prop="seqs">
            <!--            <el-select-->
            <!--              v-model="saleForm.seqs"-->
            <!--              value-key="orderCode"-->
            <!--              placeholder="请选择流转卡号"-->
            <!--              style="width: 100%"-->
            <!--              multiple-->
            <!--            >-->
            <!--              <el-option-->
            <!--                v-for="item in seqList"-->
            <!--                :key="item.label"-->
            <!--                :label="item.label"-->
            <!--                :value="item.label"-->
            <!--              />-->
            <!--            </el-select>-->
            <el-input v-model="saleForm.seqs"/>
          </el-form-item>
          <el-form-item label="数量" prop="seqNum">
            <el-input type="number" v-model="saleForm.seqNum"/>
          </el-form-item>
          <el-form-item label="产品分类" prop="type">
            <el-select
              v-model="saleForm.type"
              value-key="value"
              placeholder="请选择产品分类"
              style="width: 100%"
            >
              <el-option
                v-for="item in typeList"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="器件名称及型号" prop="componentName">
            <el-input v-model="saleForm.componentName" />
          </el-form-item>
          <el-form-item label="检验批号或生产批号" prop="checkProduceNo">
            <el-input v-model="saleForm.checkProduceNo"></el-input>
            <input v-model="saleForm.workOrderCode" hidden="true" />
          </el-form-item>
          <el-form-item label="数量" prop="num">
            <el-input v-model="saleForm.num" type="number" />
          </el-form-item>
          <el-form-item label="供方单位" prop="company">
            <el-input v-model="saleForm.company" />
          </el-form-item>
          <el-form-item label="审核类型" prop="auditType">
            <el-select
              v-model="saleForm.auditType"
              value-key="value"
              placeholder="请选择审核类型"
              style="width: 100%"
            >
              <el-option
                v-for="item in auditTypes"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="审理级别" prop="level">
            <el-select
              v-model="saleForm.level"
              value-key="value"
              placeholder="请选择审理级别"
              style="width: 100%"
            >
              <el-option
                v-for="item in levelTypes"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="发生阶段" prop="stage">
            <el-input v-model="saleForm.stage" />
          </el-form-item>
          <el-form-item label="发生日期" prop="happenTime">
            <el-date-picker
              v-model="remark1.happenTime"
              type="date"
              placeholder="请选择日期"
              clearable
              format="YYYY年MM月DD日"
              value-format="YYYY年MM月DD日"
              style="width: 100%"
              @change="updateFormHappenTime"
            />
          </el-form-item>
        </el-form>

        <el-form
          ref="remark1Ref"
          :model="remark1"
          label-width="120"
          :rules="rules1"
          style="max-width: 600px"
        >
          <el-form-item label="不合格现象（质量问题）描述" prop="content">
            <el-input v-model="remark1.content" type="textarea" />
          </el-form-item>
          <el-form-item label="填表人" prop="user">
            <!--            <el-select
              v-model="remark1.user"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in userList"
                :key="item.userName"
                :label="item.userName"
                :value="item.userName"
              />
            </el-select>-->
            <el-tree-select
              v-model="remark1.user"
              :data="userList"
              filterable
              multiple
            />
          </el-form-item>
          <!--          <el-form-item label="检验人" prop="user1">-->
          <!--            <el-tree-select-->
          <!--              v-model="remark1.user1"-->
          <!--              :data="userList"-->
          <!--              filterable-->
          <!--              multiple-->
          <!--            />-->
          <!--          </el-form-item>-->
          <el-form-item label="日期" prop="time">
            <el-date-picker
              v-model="remark1.time"
              type="date"
              placeholder="请选择日期"
              clearable
              format="YYYY年MM月DD日"
              value-format="YYYY年MM月DD日"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="下一步处理人" prop="nextRemarkUser">
            <el-tree-select
              v-model="remark1.nextRemarkUser"
              :data="userList"
              filterable
              multiple
            />
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div class="drawer-bottom">
          <el-button @click="cancelClick">取消</el-button>
          <el-button type="primary" @click="confirmClick">提交</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { addFeedback } from "@/api/unqualified/index";
import { getOrderList } from "@/api/sales/index";
import { getUserTree } from "@/api/user/index";
import { useDictionaryStore } from "@/store";
const drawerVisible = ref(false);
const disabledDate = (time) => {
  //选择今天以及今天之后的日期
  return time.getTime() < Date.now() - 8.64e7; //如果没有后面的-8.64e7就是不可以选择
  //选择今天以及今天之前的日期
  //return time.getTime() > Date.now() - 8.64e7;//如果没有后面的-8.64e7就是不可以选择今天的
};
const disabledDate1 = (time) => {
  //选择今天以及今天之后的日期
  return time.getTime() > Date.now() - 8.64e7; //如果没有后面的-8.64e7就是不可以选择
  //选择今天以及今天之前的日期
  //return time.getTime() > Date.now() - 8.64e7;//如果没有后面的-8.64e7就是不可以选择今天的
};
const { dicts } = useDictionaryStore();
const auditTypes = dicts.unqualified_audit_type;
const levelTypes = ref([
  { dictValue: "0", dictLabel: "一级" },
  { dictValue: "1", dictLabel: "二级" },
]);
const baseInfoRef = ref(null);
const saleForm = reactive({
  customer: "",
  address: "",
  contacts: "",
  phoneNo: "",
  stage: "",
  seqs: "",
});
// 顾客投诉或建议
const remark1Ref = ref(null);

const remark1 = reactive({
  content: "",
  user: "",
  time: "",
  nextRemarkUser: "",
});

const rules = {
  type: [{ required: true, message: "请选择产品分类", trigger: "blur" }],
  auditType: [{ required: true, message: "请选择审核类型", trigger: "blur" }],
  seqs: [{ required: true, message: "请选择订单信息", trigger: "change" }],
  level: [{ required: true, message: "请选择审理级别", trigger: "change" }],
  happenTime: [{required: true, message: "请选择发生时间", trigger: "change"}],
  stage: [{ required: true, message: "请输入发生阶段", trigger: "change" }],
};
const rules1 = {
  content: [
    {
      required: true,
      message: "请输入不合格现象（质量问题）描述",
      trigger: "blur",
    },
    { min: 2, max: 200, message: "长度在 2 到 200 个字符", trigger: "blur" },
  ],
  user: [
    { required: true, message: "请输入姓名", trigger: "blur" },
  ],
  user1: [{ required: true, message: "检验人员不能为空", trigger: "blur" }],
  time: [{ required: true, message: "请选择日期", trigger: "change" }],
  nextRemarkUser: [
    {required: true, message: "请选择处理人", trigger: "blur"},
    // { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
};

// 订单相关信息
const opOptions = ref([...dicts.spc_operation]);
const typeList = dicts.sales_info_type;
const allOrders = ref([]);
// 订单相关信息
const orders = ref([]);
const selectedOrder = ref({});
const orderLoading = ref(false); // 注意这里要改为ref
const selectOrderCode = ref(null); // 初始化为null
const searchQuery = ref('') // 使用ref创建的响应式变量
// 远程搜索方法 - 调用后台API
// 远程搜索方法（调用后端API）
const remoteOrderSearch = async (query) => {
  searchQuery.value = query;
  if (query === '') {
    // 如果搜索词为空，显示初始列表
    await getOrders();
    return;
  }

  orderLoading.value = true;
  try {
    const res = await getOrderList({
      pageNo: 0,
      pageSize: 200,
      workOrderCode: query,
    });
    orders.value = res.data.records || [];
  } catch (error) {
    console.error('搜索订单失败:', error);
    orders.value = [];
  } finally {
    orderLoading.value = false;
  }
};
const updateFormHappenTime = (newValue) => {

  saleForm.happenTime = newValue.replace(/年|月|日/g, match => {
    return {'年': '-', '月': '-', '日': ''}[match];
  });
  console.log(saleForm.happenTime, "dsdfds")

};
const getOrders = async () => {
  orderLoading.value = true;
  try {
    const res = await getOrderList({
      pageNo: 0,
      pageSize: 200,
    });
    orders.value = res.data.records || [];
  } catch (error) {
    console.error('获取订单列表失败:', error);
    orders.value = [];
  } finally {
    orderLoading.value = false;
  }
};
const orderSelect = (value) => {
  console.log(value);
  selectedOrder.value = value;
  // seqList.value = selectedOrder.value.seqs.map((item, index) => ({
  //   value: item,
  //   label: item,
  // }));
  saleForm.seqs = "";
  saleForm.orderNo = value.orderNo;
};

const seqList = ref([]);

// 用户信息
const userInfo = ref({});
const userList = ref([]);
const getUserInfo = async () => {
  //const res = await getUserList();
  //userList.value = res.data;
  // if (userList.value.length > 0) {
  //   userInfo.value = userList.value[0];
  // }
  getUserTree().then((data) => {
    userList.value = data.data;
  });
};

const showDrawer = () => {
  selectedOrder.value = {};
  selectOrderCode.value = {};
  getOrders();
  getUserInfo();
  drawerVisible.value = true;
};

defineExpose({ showDrawer });

const cancelClick = () => {
  drawerVisible.value = false;
  baseInfoRef.value.resetFields();
  remark1Ref.value.resetFields();
  selectedOrder.value = {};
};

const feedBackEmit = defineEmits(["finish"]);

const confirmClick = () => {
  console.log(saleForm, "11");
  console.log(remark1, 22);
  console.log(selectedOrder.value, 55);

  // drawerVisible.value = false;

  //
  // // 验证表单
  baseInfoRef.value.validate((valid) => {
    if (valid) {
      console.log("baseInfoRef valid");
    } else {
      console.log("baseInfoRef invalid");
      return false;
    }
  });
  remark1Ref.value.validate((valid) => {
    remark1.nextRemarkUser = remark1.nextRemarkUser.join(",")
    if (valid) {
      let remark1Copy = {
        content: remark1.content,
        user: remark1.user.join(","),
        user1: "",
        time: remark1.time,
      };
      let remark2 = {
        content: "",
        user2: remark1.nextRemarkUser,
        time: "",
      };

      let p = {
        ...saleForm,
        ...selectedOrder.value,
        currentUserName: remark1.nextRemarkUser,
        remark1: JSON.stringify(remark1Copy),
        remark2: JSON.stringify(remark2),
      };
      p.seqs = saleForm.seqs;

      addFeedback(p).then(() => {
        feedBackEmit("finish");
        cancelClick();
      });
    } else {
      console.log("remark1Ref invalid");
      return false;
    }
  });
};
</script>

<style scoped lang="scss">
.drawer-bottom {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
</style>
