<template>
  <div class="app-container">
    <el-card shadow="always" style="width: 55%; margin: 0 auto">
      <el-form
        ref="formRef"
        :label-width="labelWidth + 'px'"
        :model="form"
        :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('routes.company.technicalDemand'),
                })
              "
              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('webSearch.demandDescription')"
              prop="introduce"
            >
              <!--              <wangEditor
                              v-model="form.introduce"
                              min-height="150px"
                              :placeholder="t('webSearch.pleaseEnterTheContentOfTheTechnicalRequirementsAndTheDetailedTechnicalIndicators')"
                              width="100%"
                              @blur="formRef.validateField(`introduce`)"
                            ></wangEditor>-->
              <el-input
                type="textarea"
                v-model="form.introduce"
                :autosize="{ minRows: 6, maxRows: 8 }"
                :placeholder="
                  t(
                    'webSearch.pleaseEnterTheContentOfTheTechnicalRequirementsAndTheDetailedTechnicalIndicators'
                  )
                "
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <field-options
          ref="fieldFormRef"
          v-model="form"
          :labelWidth="labelWidth"
        />

        <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-group>
        <el-row>
          <el-col :span="12">
            <el-form-item
              :prop="form.budgetMode == 1 ? 'budget' : ''"
              :label="t('admin.form.achievementDemandBudget')"
            >
              <el-input
                v-model="form.budget"
                oninput="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
                :placeholder="
                  t('admin.form.placeholder', {
                    type: t('admin.form.technicalDemandBudget'),
                  })
                "
              >
                <template #append
                  >{{ t("admin.table.tenThousandYuan") }}
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="50px">
              <el-checkbox
                v-model="form.budgetMode"
                false-label="1"
                true-label="2"
                >{{ t("tips.faceToFace") }}
              </el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item :label="t('admin.table.deadline')" prop="deadline">
              <el-date-picker
                v-model="form.deadline"
                :placeholder="
                  t('admin.form.pleaseSelect', {
                    type: t('admin.table.deadline'),
                  })
                "
                style="width: 100%"
                type="date"
                value-format="YYYY-MM-DD"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div :style="{ marginLeft: labelWidth + 'px' }">
        <el-button type="primary" @click=""> {{ t("common.close") }}</el-button>
      </div>
    </el-card>
  </div>
</template>
<script setup>
// import { expert } from "@/api/identity/index";
// import { insertTechnologyDemand } from "@/api/admin/enterprise";
import tab from "@/plugins/tab";
import FieldOptions from "@/views/components/FieldOptions";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import {
  getTechnologyDemand,
  insertTechnologyDemand,
  updateTechnologyDemand,
} from "@/api/admin/enterprise/demand";
import { getCurrentInstance, onMounted, reactive, ref, toRefs } from "vue";
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: [],
  },
  rules: {},
});

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

const { proxy } = getCurrentInstance();
const labelWidth = 160;
// const isContainOther = ref(false);
const checkList = reactive([
  {
    id: 1,
    name: "成果推广",
  },
  {
    id: 2,
    name: "关键成果解决",
  },
  {
    id: 3,
    name: "对接专家院士",
  },
  {
    id: 4,
    name: "上市辅导",
  },
]);

const formRef = ref(null);
const fieldFormRef = ref(null);
const directionsFormRef = ref(null);
const checkInput = ref("");
const submitForm = async (status) => {
  let formValid;
  try {
    formValid = await formRef.value.validate();
  } catch (error) {
    formValid = false;
  }
  form.value.status = status;
  const fieldFormValid = await fieldFormRef.value.validateForm();
  const directionsFormValid = await directionsFormRef.value.validateForm();
  if (formValid && fieldFormValid && directionsFormValid) {
    if (route.query.id) {
      await updateTechnologyDemand(form.value);
      ElMessage.success(t("admin.common.EditSuccess"));
    } else {
      await insertTechnologyDemand(form.value);
      ElMessage.success(t("admin.common.addSuccess"));
    }
    updateCount("technology");
    backToList();
  } else {
    console.log("validation failed");
  }
};

// 返回技术需求列表
const backToList = () => {
  tab.closeOpenPage({ path: "/demand/technology" });
};

/*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();
  return;
  if (route.query.id) {
    getTechnologyDemand({ id: route.query.id }).then((resp) => {
      form.value = resp.data;

      if (!form.value.kinds) {
        form.value.kinds = resp.data.kind?.split(",") ?? [];
        form.value.kinds.forEach((el, index) => {
          if (!checkList.find((item) => item.name == el)) {
            checkList.push({
              id: index,
              name: el,
            });
          }
        });
      }
      if (!form.value.wants) {
        form.value.wants = resp.data.want?.split(",") ?? [];
      }
    });
  } else {
    form.value = {
      check: [],
    };
    if (formRef.value) {
      formRef.value.resetFields();
    }
  }
});
</script>
<style lang="scss" scoped>
:deep(.cooperation-mode) {
  .input-add-bar {
    width: 100%;
  }
}
</style>
