<template>
  <div class="app-container">
    <el-card shadow="always" style="width: 55%; margin: 0 auto">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-width="labelWidth + 'px'"
      >
        <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="form.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') })
              "
            >
              <el-checkbox-group v-model="form.kinds">
                <el-checkbox
                  v-for="item in checkList"
                  :key="item.id"
                  :label="item.name"
                  >{{ item.name }}
                </el-checkbox>
                <!-- <el-checkbox label="0" @change="handleCheck">其他</el-checkbox> -->
              </el-checkbox-group>
              <el-row :gutter="20">
                <el-col :span="20">
                  <el-input
                    v-model="checkInput"
                    placeholder="请输入需求类别"
                  ></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"
            >
              <!-- <Editor v-model="form.description" :minHeight="150" /> -->
              <!--              <wangEditor
                              v-model="form.description"
                              width="100%"
                              min-height="150px"
                              @blur="formRef.validateField(`description`)"
                            ></wangEditor>-->
              <el-input
                type="textarea"
                v-model="form.description"
                :autosize="{ minRows: 6, maxRows: 8 }"
                :placeholder="
                  t('admin.form.placeholder', {
                    type: t('webSearch.demandDescription'),
                  })
                "
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <CityOptions
          v-model="form"
          :labelWidth="labelWidth"
          ref="cityFormRef"
        /> -->

        <el-row>
          <el-col :span="12">
            <el-form-item :label="t('admin.form.demandContact')" prop="name">
              <el-input
                v-model="form.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="form.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="t('admin.table.demandSubmitter')"
              prop="commitUserName"
            >
              <el-input
                v-model="form.commitUserName"
                :placeholder="
                  t('admin.form.placeholder', {
                    type: t('admin.table.demandSubmitter'),
                  })
                "
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="t('admin.form.demandSubmitterPhone')"
              prop="commitPhone"
            >
              <el-input
                v-model="form.commitPhone"
                :placeholder="t('admin.form.demandSubmitterPhone')"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div :style="{ marginLeft: labelWidth + 'px' }">
        <el-button @click="backToList"
          >{{ 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 tab from "@/plugins/tab";
import {
  getDemand,
  insertDemand,
  updateDemand,
} from "@/api/admin/enterprise/demand";
import { ElMessage } from "element-plus";
import { computed, onMounted, reactive, toRefs } from "vue";
import { demandCategoryList } from "@/utils/parameter";
import { useRoute, useRouter } from "vue-router";
import { updateCount } from "@/api/admin/count";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const router = useRouter();
const route = useRoute();
const data = reactive({
  form: {
    check: [],
    status: 1,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    postCode: undefined,
  },
  rules: {
    title: [
      {
        required: true,
        /*"需求名称不能为空"*/
        message: computed(() =>
          t("admin.validation.required", {
            type: t("admin.form.name", {
              type: t("admin.common.demand"),
            }),
          })
        ),
        trigger: "blur",
      },
    ],
    description: [
      {
        required: true,
        /*"需求描述不能为空"*/
        message: computed(() =>
          t("admin.validation.required", {
            type: t("webSearch.demandDescription"),
          })
        ),
        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.contactPhone"),
          })
        ),
        trigger: "blur",
      },
    ],
    username: [
      {
        required: true,
        message: computed(() => t("webContact.demandSubmit")),
        trigger: "blur",
      },
    ],
    userPhone: [
      {
        required: true,
        /*"手机号不能为空"*/
        message: computed(() =>
          t("admin.validation.required", { type: t("admin.form.mobile") })
        ),
        trigger: "blur",
      },
    ],
  },
});

const { form, rules } = toRefs(data);

const labelWidth = 140;
const checkList = reactive([...demandCategoryList]);
const checkInput = ref("");
// const cityFormRef = ref();
const formRef = ref();
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    // const cityFormValid = cityFormRef.value.validateForm(); // 城市
    if (valid) {
      if (form.value.id != undefined) {
        await updateDemand(form.value);
        ElMessage.success(t("admin.common.editSuccess"));
        // router.back();
      } else {
        await insertDemand(form.value);
        ElMessage.success(t("admin.common.AddSuccess"));
        // router.back();
        updateCount("service");
      }

      backToList();
    }
  });
};

// 返回服务需求列表
const backToList = () => {
  tab.closeOpenPage({ path: "/demand/serviceDemand" });
};

// 添加需求类别时验证
function addCheck() {
  if (!checkInput.value.trim().length) return ElMessage.error("请输入");
  const flag = checkList.some((item) => {
    return item.name.trim() == checkInput.value.trim();
  });
  if (!flag) {
    checkList.push({
      id: checkList.length + 1,
      name: checkInput.value,
    });
    checkInput.value = "";
  }
}

onMounted(() => {
  formRef.value.resetFields();
  if (route.query.id) {
    const obj = Object.assign({}, route, { title: "修改服务需求" });
    tab.updatePage(obj);
    getDemand({ id: route.query.id }).then((resp) => {
      if (resp.data.kinds) {
        resp.data.kinds.forEach((el, index) => {
          if (!checkList.find((item) => item.name == el)) {
            checkList.push({
              id: index,
              name: el,
            });
          }
        });
      }
      form.value = resp.data;
    });
  } else {
    form.value = {
      check: [],
      status: 0,
    };
    if (formRef.value) {
      formRef.value.resetFields();
    }
  }
});
</script>
