<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="顾客名称" prop="customer">
            <el-input v-model="saleForm.customer"/>
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="saleForm.address"/>
          </el-form-item>
          <el-form-item label="联系人" prop="contacts">
            <el-input v-model="saleForm.contacts"/>
          </el-form-item>

          <el-form-item label="联系电话" prop="phoneNo">
            <el-input v-model="saleForm.phoneNo"/>
          </el-form-item>
          <!--          <el-form-item label="阶段" prop="stage">
            <el-input v-model="saleForm.stage" />
          </el-form-item>-->
          <el-form-item label="检验批号">
            <el-select
              v-model="selectCheckCode"
              value-key="checkCode"
              placeholder="请选择检验批号"
              style="width: 100%"
              @change="orderSelect"
              filterable
            >
              <el-option
                v-for="item in orders"
                :key="item.checkCode"
                :label="item.checkCode"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="产品型号">
            <el-select
              v-model="selectMaterialModel"
              value-key="materialModel"
              placeholder="请选择产品型号"
              style="width: 100%"
              @change="modelSelect"
              filterable
            >
              <el-option
                v-for="item in selectdMaterialModel"
                :key="item.materialModel"
                :label="item.materialModel"
                :value="item"
              />
            </el-select>
          </el-form-item>

          <!--          <el-form-item label="检验批号">
            <div>{{ selectedOrder.workOrderCode }}</div>
          </el-form-item>-->

          <el-form-item label="产品编号" prop="seqs">
            <el-select
              v-model="saleForm.seqs"
              @change="handleSelectAll"
              value-key="orderCode"
              placeholder="请选择流转卡号"
              style="width: 100%"
              filterable
              multiple
            >
              <!-- 全选选项 -->
              <el-option
                label="全选"
                :value="allSelectValue"
              />

              <el-option
                v-for="item in seqList"
                :key="item.label"
                :label="item.label"
                :value="item.label"
              />
            </el-select>
          </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>

        <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="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,
  getCheckList,
  getOrderList,
  getUserList,
  getMaterialList,
  getSeqNoList,
} 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 {dicts} = useDictionaryStore();
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 = {
  customer: [
    {required: true, message: "请输入顾客名称", trigger: "blur"},
    {min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur"},
  ],
  address: [
    {required: true, message: "请输入详细地址", trigger: "blur"},
    {min: 2, max: 200, message: "长度在 2 到 200 个字符", trigger: "blur"},
  ],
  contacts: [
    {required: true, message: "请输入联系人", trigger: "blur"},
    {min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur"},
  ],
  phoneNo: [
    {required: true, message: "请输入联系电话", trigger: "blur"},
    {min: 11, max: 11, message: "请输入正确的手机号", trigger: "blur"},
  ],
  seqs: [{required: true, message: "请选择产品分类", trigger: "change"}],
  materialModel: [{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"},
  ],
  time: [{required: true, message: "请选择日期", trigger: "change"}],
  nextRemarkUser: [
    {required: true, message: "请选择处理人", trigger: "blur"},
  ],
};

// 订单相关信息
const orders = ref([]);
const typeList = dicts.sales_info_type;
const selectedCheckCode = ref({});
const selectdMaterialModel = ref({});
const selectMaterialModel = ref("");
const selectCheckCode = ref("");
const allSelectValue = ref("ALL_SELECT_MAGIC_VALUE"); // 全选的特殊值
const handleSelectAll = (selectedValues) => {
  const allLabels = seqList.value.map(item => item.label);
  const allSelected = allLabels.length > 0 &&
    allLabels.every(label => selectedValues.includes(label));

  // 如果点击了"全选"选项
  if (selectedValues.includes(allSelectValue.value)) {
    saleForm.seqs = allSelected ? [] : [...allLabels];
    return;
  }

  // 如果手动选择了所有选项（不通过全选按钮）
  if (selectedValues.length === allLabels.length && allLabels.length > 0) {
    // 保持纯净值，不添加全选标识
    saleForm.seqs = [...allLabels];
    return;
  }

  // 其他情况直接使用选择的值
  saleForm.seqs = selectedValues;
}
const getOrders = async () => {
  const res = await getCheckList({});
  orders.value = res.data;
  if (orders.value.length > 0) {
    // selectCheckCode.value = orders.value[0].orderCode;
    // selectedOrder.value = orders.value[0];
  }
};
const orderSelect = (value) => {
  selectedCheckCode.value = value;
  console.log(value, "ppp")

  saleForm.seqs = [];
  saleForm.materialModel = "";
  saleForm.materialName = "";
  saleForm.materialCode = "";
  selectMaterialModel.value = "";
  getMaterialList(value.checkCode, "").then((res) => {
    console.log(res);
    selectdMaterialModel.value = res.data;
  });
  console.log(selectdMaterialModel, "lizil")
};
const modelSelect = (value) => {
  console.log(value, "6666")
  saleForm.materialModel = value.materialModel;
  saleForm.materialName = value.materialName;
  saleForm.materialCode = value.materialCode;
  saleForm.seqs = [];
  seqList.value = [];
  getSeqNoList(value.checkCode, value.materialModel, "").then((res) => {
    console.log(res);
    seqList.value = res.data.seqs.map((item, index) => ({
      value: item,
      label: item,
    }));
    console.log(seqList, "woani")
  });

  // console.log(selectdMaterialModel,"lizil")
};

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 = () => {
  selectedCheckCode.value = {};
  selectCheckCode.value = {};
  selectMaterialModel.value = {};
  getOrders();
  getUserInfo();
  drawerVisible.value = true;
};

defineExpose({showDrawer});

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

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

const confirmClick = () => {
  console.log(saleForm);
  console.log(remark1);

  // drawerVisible.value = false;

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

      let p = {
        ...saleForm,
        ...selectedCheckCode.value,
        materialModel: saleForm.materialModel,
        materialName: saleForm.materialName,
        materialCode: saleForm.materialCode,
        currentUserName: remark1.nextRemarkUser.join(","),
        remark1: JSON.stringify(remark1Copy),
        remark2: JSON.stringify(remark2),
      };

      p.seqs = saleForm.seqs.join(",");

      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>
