<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>基本信息</b></p>

        <el-row>
          <el-col :span="24">
            <el-form-item label="技术需求名称:" prop="title">
              <el-input v-model="form.title"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <!--           <el-checkbox label="0" @change="handleCheck">其他</el-checkbox>-->
            <el-form-item label="需求类别:" prop="kinds">
              <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 :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">添加</el-button>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="需求描述:" prop="introduce">
              <wangEditor
                v-model="form.introduce"
                min-height="150px"
                placeholder="请输入技术需求内容和详细的技术指标"
                width="100%"
                @blur="formRef.validateField(`introduce`)"
              ></wangEditor>
            </el-form-item>
          </el-col>
        </el-row>

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

        <el-row>
          <el-col :span="12">
            <el-form-item
              :prop="form.budgetMode == 1 ? 'budget' : ''"
              label="成果需求预算:"
            >
              <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="请输入技术需求预算"
              >
                <template #append>万元</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"
                >面议
              </el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="截止时间:" prop="deadline">
              <el-date-picker
                v-model="form.deadline"
                placeholder="请选择截止时间"
                style="width: 100%"
                type="date"
                value-format="YYYY-MM-DD"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="需求联系人:" prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入需求联系人"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人手机号:" prop="mobile">
              <el-input
                v-model="form.mobile"
                maxlength="11"
                placeholder="请输入联系人手机号"
              ></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="form.commitUserName"
                placeholder="请输入需求提交人"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="需求提交人手机号:" prop="commitUserPhone">
              <el-input
                v-model="form.commitUserPhone"
                placeholder="请输入需求提交人手机号"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row> -->

        <el-row>
          <el-col :span="24">
            <input-box-add
              ref="directionsFormRef"
              v-model="form"
              :labelWidth="labelWidth"
              class="cooperation-mode"
              fieldKey="wants"
              placeholder="合作开发、委托研发、技术转让、技术入股、技术许可"
              title="合作模式"
            />
          </el-col>
        </el-row>
      </el-form>
      <!-- <div :style="{ marginLeft: labelWidth + 'px' }">
        <el-button @click="router.go(-1)">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </div> -->
      <div :style="{ marginLeft: labelWidth + 'px' }">
        <el-button type="primary" @click="submitForm(3)">保存草稿</el-button>
        <el-button type="primary" @click="submitForm(1)">提交审核</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 CityOptions from "@/views/components/CityOptions";
import FieldOptions from "@/views/components/FieldOptions";
import InputBoxAdd from "@/views/components/InputBoxAdd";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import { getTechnologyDemand } from "@/api/admin/enterprise/demand";
import { onMounted, reactive, ref, toRefs } from "vue";
import { updateCount } from "@/api/admin/count";
import { insertDemand } from "@/api/admin/agent/service/technology-demand";

const router = useRouter();
const route = useRoute();
const data = reactive({
  form: {
    check: [],
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    postCode: undefined,
  },
  rules: {
    title: [{ required: true, message: "需求名称不能为空", trigger: "blur" }],
    introduce: [
      { required: true, message: "需求描述不能为空", trigger: "change" },
    ],
    name: [{ required: true, message: "需求联系人不能为空", trigger: "blur" }],
    mobile: [
      { required: true, message: "联系人手机号不能为空", trigger: "blur" },
      {
        pattern: /^1[3456789]\d{9}$/,
        message: "手机号格式不正确",
        trigger: "blur",
      },
    ],
    commitUserName: [
      { required: true, message: "需求提交人不能为空", trigger: "blur" },
    ],
    kinds: [
      { required: true, message: "至少选择一个需求类别", trigger: "change" },
    ],
    budget: [{ required: true, message: "需求预算不能为空", trigger: "blur" }],
    deadline: [
      {
        required: true,
        message: "请选择截止时间",
        trigger: ["change", "blur"],
      },
    ],
    commitUserPhone: [
      { required: true, message: "需求提交人手机号不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, 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 cityFormRef = 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();
  const cityFormValid = await cityFormRef.value.validateForm();
  if (formValid && fieldFormValid && directionsFormValid && cityFormValid) {
    if (route.query.id) {
      /*TODO*/
      /*await updateTechnologyDemand(form.value);
      ElMessage.success("修改需求成功");*/
    } else {
      await insertDemand(form.value);
      ElMessage.success("新增需求成功");
    }
    updateCount("technology");
    backToList();
  } else {
    console.log("校验未通过");
  }
};

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

const addCheck = () => {
  if (!checkInput.value.trim().length) return proxy.$modal.msgError("请输入");
  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);
    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%;
  }
}
//:deep(.el-table--large) {
//font-size: 18px;
//th {
//font-size: 18px;
//}
//}
</style>
