<template>
  <div class="app-container">
    <el-card shadow="always" style="width: 55%; margin: 0 auto">
      <el-form
        ref="formRef"
        :label-width="labelWidth + 'px'"
        :model="formData"
        :rules="rules"
      >
        <p>
          <b> {{ t("admin.form.basicInfo") }}</b>
        </p>
        <el-row>
          <el-col :span="24">
            <el-form-item
              :label="t('admin.form.name', { type: t('admin.common.demand') })"
              prop="title"
            >
              <el-input v-model="formData.title"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item
              :label="
                t('admin.form.category', { type: t('admin.common.demand') })
              "
              prop="kinds"
            >
              <el-checkbox-group v-model="formData.kinds">
                <el-checkbox
                  v-for="item in checkList"
                  :key="item.id"
                  :label="locale === 'zh' ? item.name : item[labelField]"
                  >{{ locale === "zh" ? item.name : item[labelField] }}
                </el-checkbox>
              </el-checkbox-group>
              <el-row :gutter="20">
                <el-col :span="20">
                  <el-input
                    v-model="checkInput"
                    :placeholder="
                      t('admin.form.placeholder', {
                        type: t('webSearch.demandType'),
                      })
                    "
                  ></el-input>
                </el-col>
                <el-col :span="4">
                  <el-button type="primary" @click="addCheck"
                    >{{ t("admin.common.add") }}
                  </el-button>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item
              :label="t('webSearch.demandDescription')"
              prop="description"
            >
              <!--              <wangEditor-->
              <!--                ref="wangEditorRef"-->
              <!--                v-model="formData.description"-->
              <!--                min-height="150px"-->
              <!--                width="100%"-->
              <!--                @blur="formRef.validateField(`description`)"-->
              <!--              ></wangEditor>-->
              <el-input
                type="textarea"
                v-model="formData.description"
                :autosize="{ minRows: 6, maxRows: 8 }"
                :placeholder="
                  t('admin.form.placeholder', {
                    type: t('webSearch.demandDescription'),
                  })
                "
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!--COMPLETED-->
        <!--        <el-form-item :label="t('admin.form.country')" prop="country">
          <el-select
              v-model="formData.country"
              :placeholder="
          t('admin.form.pleaseSelect', { type: t('admin.form.country') })
        "
          >
            <el-option
                v-for="option in countryOptions"
                :label="option[locale]"
                :value="option.key"
            />
          </el-select>
        </el-form-item>-->

        <el-row>
          <el-col :span="12">
            <el-form-item :label="t('admin.form.demandContact')" prop="name">
              <el-input
                v-model="formData.name"
                :placeholder="
                  t('admin.form.placeholder', {
                    type: t('admin.form.demandContact'),
                  })
                "
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="t('admin.form.contactPhone')" prop="mobile">
              <el-input
                v-model="formData.mobile"
                :placeholder="
                  t('admin.form.placeholder', {
                    type: t('admin.form.contactPhone'),
                  })
                "
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!--        <el-row>-->
        <!--          <el-col :span="12">-->
        <!--            <el-form-item label="需求提交人:" prop="commitUserName">-->
        <!--              <el-input-->
        <!--                v-model="formData.commitUserName"-->
        <!--                placeholder="请输入需求提交人"-->
        <!--              ></el-input>-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--          <el-col :span="12">-->
        <!--            <el-form-item label="提交人手机号:" prop="commitPhone">-->
        <!--              <el-input-->
        <!--                v-model="formData.commitPhone"-->
        <!--                placeholder="请输入需求提交人手机号"-->
        <!--              ></el-input>-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--        </el-row>-->
      </el-form>
      <div :style="{ marginLeft: labelWidth + 'px' }">
        <el-button @click="back">{{ t("admin.common.cancel") }}</el-button>
        <el-button type="primary" @click="submitForm"
          >{{ t("admin.common.submit") }}
        </el-button>
      </div>
    </el-card>
  </div>
</template>
<script setup>
// import { expert } from "@/api/identity/index";
import {
  getDemandById,
  insertDemand,
  updateDemand,
} from "@/api/admin/expert/demand";
import { countryOptions, demandCategoryList } from "@/utils/parameter";
import { uniqueId } from "lodash";
import tab from "@/plugins/tab"; // import CityOptions from "@/views/components/CityOptions";
import { ElMessage } from "element-plus";
import { useRoute } from "vue-router";
import { updateCount } from "@/api/admin/count.js";
import { computed, reactive, ref, toRefs } from "vue";
import { useI18n } from "vue-i18n";
import { toTitleCase } from "@/utils/string";

const { t, locale } = useI18n();
const data = reactive({
  formData: {
    check: [],
    status: 1,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    // postCode: undefined,
  },
  rules: {
    kinds: [
      {
        required: true,
        message: computed(() =>
          t("admin.validation.required", { type: t("webSearch.demandType") })
        ),
      },
    ],
    title: [
      {
        required: true,
        /*"需求名称不能为空"*/
        message: computed(() =>
          t("admin.validation.required", {
            type: t("webSearch.name", {
              type: t("admin.common.demand"),
            }),
          })
        ),
        trigger: "blur",
      },
    ],
    description: [
      {
        required: true,
        trigger: "blur",
        /*"需求描述不能为空"*/
        message: computed(() =>
          t("admin.validation.required", {
            type: t("webSearch.demandDescription"),
          })
        ),
      },
    ],
    bankAccount: [
      {
        required: true,
        /*"需求联系人不能为空"*/
        message: computed(() =>
          t("admin.validation.required", {
            type: t("admin.form.demandContact"),
          })
        ),
        trigger: "blur",
      },
    ],
    bankPhone: [
      {
        required: true,
        /*"联系人手机号不能为空"*/ message: computed(() =>
          t("admin.form.contactPhone")
        ),
        trigger: "blur",
      },
    ],
    username: [
      {
        required: true,
        message: computed(() => t("webContact.demandSubmit")),
        trigger: "blur",
      },
    ],
    name: [
      {
        required: true,
        /*"需求联系人不能为空"*/
        message: computed(() =>
          t("admin.validation.required", {
            type: t("admin.form.demandContact"),
          })
        ),
        trigger: "blur",
      },
    ],
    mobile: [
      {
        required: true,
        /*"需求联系人手机号不能为空"*/
        message: computed(() =>
          t("admin.validation.required", { type: t("admin.form.mobile") })
        ),
        trigger: "blur",
      },
    ],
    // commitUserName: [
    //   { required: true, message: computed(()=>t('webContact.demandSubmit')), trigger: "blur" },
    // ],
    // commitPhone: [
    //   { required: true, message: "需求提交人手机号不能为空", trigger: "blur" },
    // ],
  },
});

const { queryParams, formData, rules } = toRefs(data);

const route = useRoute();
const formRef = ref();

const labelField = computed(() => {
  return locale.value === "zh" ? "name" : `name${toTitleCase(locale.value)}`;
});
const back = () => {
  tab.closeOpenPage({ path: "/demand/serviceDemand" });
};
const labelWidth = 140;
// const isContainOther = ref(false);
const checkList = reactive([...demandCategoryList]);
const checkInput = ref("");

async function submitForm() {
  await formRef.value.validate();
  if (formData.value.id) {
    // TODO: 修改专家需求
    await updateDemand(formData.value);
    ElMessage.success(t("admin.common.editSuccess"));
  } else {
    await insertDemand(formData.value);
    ElMessage.success(t("admin.common.addSuccess"));
  }
  updateCount("service");

  tab.closeOpenPage({ path: "/demand/serviceDemand" });
}

function addCheck() {
  if (!checkInput.value.trim().length) return ElMessage.error(t("input.input"));
  const flag = checkList.some((item) => {
    return item[labelField.value].trim() == checkInput.value.trim();
  });
  if (!flag) {
    checkList.push({
      id: checkList.length + 1,
      [labelField.value]: checkInput.value,
    });
    checkInput.value = "";
  }
}

const getDetail = async () => {
  const resp = await getDemandById(route.query.id);
  formData.value = resp.data;
  for (const item of resp.data.kinds) {
    if (!checkList.find((el) => el[labelField.value] === item)) {
      checkList.push({ id: uniqueId("unq-"), [labelField.value]: item });
    }
  }
};
if (route.query.id) {
  const obj = Object.assign({}, route, {
    title: t("admin.form.edit", {
      type: t("admin.common.demand"),
    }),
  });
  tab.updatePage(obj);
  getDetail();
}
</script>
