<template>
  <div style="width: 100%">
    <!-- <el-form-item label="客户来源：" prop="sourceName" required :rules="sourceRule" size="small"> -->
    <template v-if="editStatus">
      <table style="border-spacing: 0; width: 100%">
        <tr>
          <td>
            <el-select
              style="width: 100%"
              v-model.trim="sourceCategoryId"
              placeholder="客户来源分类"
              size="small"
              @change="handlerChangeCategory"
            >
              <el-option
                v-for="item in sourceCategories"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              />
            </el-select>
          </td>
          <td>
            <el-autocomplete
              :fetch-suggestions="querySearchAsync"
              :disabled="
                !sourceCategoryId || currentSource.referrerDataSource === ''
              "
              :trigger-on-focus="true"
              style="width: 100%"
              v-model="formData.sourceName"
              placeholder="请先选择左侧"
              popper-class="my-autocomplete"
              @select="handleSelectEmployee"
            >
              <template #default="{ item }">
                <div
                  style="
                    display: flex;
                    flex-direction: row;
                    justify-content: space-between;
                  "
                  v-if="currentSource.referrerDataSource === 'channel'"
                >
                  <div class="name" style="font-size: 12px">
                    {{ item.name }}
                  </div>
                </div>
                <div
                  style="
                    display: flex;
                    flex-direction: row;
                    justify-content: space-between;
                  "
                  v-if="currentSource.referrerDataSource === 'company'"
                >
                  <div class="name" style="font-size: 12px">
                    {{ item.name }}
                  </div>
                  <span class="code" style="font-size: 10px; color: darkgrey">{{
                    item.shortName
                  }}</span>
                </div>

                <div
                  style="
                    display: flex;
                    flex-direction: row;
                    justify-content: space-between;
                  "
                  v-if="currentSource.referrerDataSource === 'employee'"
                >
                  <div class="name" style="font-size: 12px">
                    {{ item.nickName }}
                  </div>
                  <span class="code" style="font-size: 10px; color: darkgrey">{{
                    item.userName
                  }}</span>
                </div>
              </template>
            </el-autocomplete>
          </td>
        </tr>
      </table>
    </template>
    <span v-else>{{
      (formData.sourceCategoryName ? formData.sourceCategoryName : "") +
      " - " +
      (formData.sourceName ? formData.sourceName : "")
    }}</span>
    <!-- </el-form-item> -->
    <DialogEmployeeChoice
      ref="DialogEmployeeChoiceRef"
      :multiple="false"
      :width="'800px'"
      @choice="simpleSelectedEmployee"
    />
    <DialogCustomerChoice
      ref="DialogCustomerChoiceRef"
      :multiple="false"
      :width="'800px'"
      @choice="simpleSelectedCustomer"
    />
    <DialogChannelChoice
      ref="DialogChannelChoiceRef"
      :multiple="false"
      :width="'800px'"
      @choice="simpleSelectedChannel"
    />
  </div>
</template>
<script setup>
import { toRef } from "vue";
import { listUser } from "@/api/system/user";
import { listChannel } from "@/api/business/channel";
import { listCompany } from "@/api/business/crm/company";
import { listSource } from "@/api/settings/source";
import DialogEmployeeChoice from "@/views/dialog/DialogEmployeeChoice.vue";
import DialogCustomerChoice from "@/views/dialog/DialogCustomerChoice.vue";
import DialogChannelChoice from "@/views/dialog/DialogChannelChoice.vue";

const { proxy } = getCurrentInstance();

const props = defineProps({
  editStatus: {
    type: Boolean,
    default: () => {},
  },
  formData: {
    type: Object,
    default: () => {},
  },
  sourceCategories: {
    type: Array,
    default: () => [],
  },
});

const sourceRule = ref({
  sourceName: [{ validate: sourceValidator, trigger: "blur" }],
});

function sourceValidator(rule, value, callback) {
  if (formData.value.sourceCategoryName === "") {
    callback(new Error("来源类型不能为空"));
    return;
  }
  if (
    formData.value.referrerDataSource !== "" &&
    formData.value.sourceName === ""
  ) {
    callback(new Error("来源不能为空"));
    return;
  }
  return callback();
}

const DialogCustomerChoiceRef = ref(null);
const DialogChannelChoiceRef = ref(null);
const DialogEmployeeChoiceRef = ref(null);
const { editStatus, formData, sourceCategories } = toRefs(props);
const data = reactive({
  placeholderValue: "请先选择左侧",
  sourceCategoryId: "",
  sourceName: "",
  currentSource: {},
});

const { placeholderValue, sourceCategoryId, sourceName, currentSource } =
  toRefs(data);

watch(
  () => formData.value.sourceCategoryId,
  (val) => {
    // console.log(formData.value.sourceCategoryId)
    sourceCategoryId.value = val;
    // formData.value.sourceId = null
    // formData.value.sourceName = ''
    handlerSelectCategory();
  }
);

watch(
  () => formData.value.sourceName,
  (val) => {
    sourceName.value = val;
    // console.log(sourceName.value)
  }
);

function handleSelectEmployee(item) {
  // 根据选择id获取数据
  if (currentSource.value.referrerDataSource === "channel") {
    formData.value.sourceName = item.name;
    formData.value.sourceId = item.id;
  } else if (currentSource.value.referrerDataSource === "employee") {
    formData.value.sourceName = item.nickName;
    formData.value.sourceId = item.userId;
  } else if (currentSource.value.referrerDataSource === "company") {
    formData.value.sourceName = item.name;
    formData.value.sourceId = item.id;
  }
}
function handlerChangeCategory(value) {
  formData.value.sourceId = null;
  formData.value.sourceName = "";
  handlerSelectCategory();
}

function handlerSelectCategory() {
  formData.value.sourceCategoryId = sourceCategoryId.value;
  formData.value.referrerDataSource = currentSource.value.referrerDataSource;
  const index = sourceCategories.value.findIndex(
    (l) => l.id === sourceCategoryId.value
  );
  currentSource.value = index >= 0 ? sourceCategories.value[index] : {};
  var item = sourceCategories.value.find(
    (emp) => emp.id === sourceCategoryId.value
  );
  if (item) {
    formData.value.sourceCategoryName = item.title;
    formData.value.referrerDataSource = item.referrerDataSource;
    // placeholderValue.value = item.title + "名称";
  }

  // // 咋整都要清理 右侧
  // sourceName.value = "";
}

/** 输入框输出建议 */
function querySearchAsync(queryString, cb) {
  console.log("输出建议", currentSource.value);
  // 根据选择id获取数据
  if (currentSource.value.referrerDataSource === "channel") {
    const query = { name: queryString };
    listChannel(query).then((res) => {
      cb(res.rows);
    });
  } else if (currentSource.value.referrerDataSource === "employee") {
    const query = { keyword: queryString };
    listUser(query).then((res) => {
      cb(res.rows);
    });
  } else if (currentSource.value.referrerDataSource === "company") {
    const query = { keyword: queryString };
    listCompany(query).then((res) => {
      cb(res.rows);
    });
  }
}

function handlerInputOpen() {
  // 根据选择id,打开对话框
  if (currentSource.value.referrerDataSource === "channel") {
    DialogChannelChoiceRef.value.open();
  } else if (currentSource.value.referrerDataSource === "employee") {
    DialogEmployeeChoiceRef.value.open();
  } else if (currentSource.value.referrerDataSource === "company") {
    DialogCustomerChoiceRef.value.open();
  }
}

function simpleSelectedEmployee(_info) {
  sourceName.value = _info.nickName;
  formData.value.sourceId = _info.userId;
  formData.value.sourceName = _info.nickName;
  // proxy.$refs.DialogEmployeeChoice.close()
}

function simpleSelectedCustomer(_info) {
  sourceName.value = _info.name;
  formData.value.sourceId = _info.id;
  formData.value.sourceName = _info.name;
  // proxy.$refs.DialogCustomerChoice.close()
}

function simpleSelectedChannel(_info) {
  sourceName.value = _info.name;
  formData.value.sourceId = _info.id;
  formData.value.sourceName = _info.name;
  // proxy.$refs.DialogChannelChoice.close()
}

function simpleSelectedDepart(_info) {
  sourceName.value = _info.employeeName;
  formData.value.sourceId = _info.employeeId;
  formData.value.sourceName = _info.employeeName;
  // proxy.$refs.DialogDepartmentEmployeeChoice.close()
}
function reset() {
  sourceCategoryId.value = null;
  sourceName.value = "";
  formData.value.sourceId = null;
  formData.value.sourceName = "";
  formData.value.sourceCategoryId = null;
}
function setForm(form) {
  formData.value = form;
}
function sourceable() {
  return currentSource.value.referrerDataSource !== "";
}
defineExpose({
  reset,
  setForm,
});
</script>
