<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          size="small"
          @click="handleAdd"
        >
          {{ t("admin.common.add") }}
        </el-button>
      </el-col>
      <!-- <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar> -->
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="dataList">
      <el-table-column :label="t('admin.common.dataNumber')" prop="id" />
      <el-table-column
        :label="t('admin.form.name', { type: t('admin.common.company') })"
        prop="enterpriseName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('admin.form.location')"
        prop="address"
        :show-overflow-tooltip="true"
      />
      <!-- province--city--district -->
      <el-table-column :label="t('admin.form.industry')" prop="territoryStr" />
      <el-table-column :label="t('admin.form.contact')" prop="contactUser" />
      <el-table-column :label="t('webContact.phone')" prop="contactPhone" />
      <!-- <el-zh-column label="创建日期" align="center" prop="created_at">
        <template #default="{ row }">
          <span>{{ dayjs(row.created_at).format("YYYY-MM-DD HH:mm:ss") }}</span>
        </template>
      </el-zh-column> -->
      <el-table-column
        :label="t('admin.common.operation')"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="{ row }">
          <el-button
            size="small"
            type="text"
            icon="Edit"
            @click="handleUpdate(row)"
            >{{ t("admin.common.edit") }}
          </el-button>
          <el-button
            size="small"
            type="text"
            icon="Delete"
            @click="handleDelete(row.id)"
          >
            {{ t("admin.common.delete") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改数据配置对话框 -->
    <el-dialog
      :title="title"
      v-model="showEditDialog"
      width="750px"
      append-to-body
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item
          :label="t('admin.form.name', { type: t('admin.common.company') })"
          prop="enterpriseName"
        >
          <el-input
            v-model="form.enterpriseName"
            :placeholder="
              t('admin.form.placeholder', { type: t('admin.common.company') })
            "
          />
        </el-form-item>
        <el-form-item :label="t('admin.form.contact')">
          <el-input
            v-model="form.contactUser"
            :placeholder="
              t('admin.form.placeholder', {
                type: t('admin.form.expertName'),
              })
            "
          />
        </el-form-item>
        <el-form-item :label="t('webContact.phone')">
          <el-input
            v-model="form.contactPhone"
            :placeholder="t('admin.form.defaultExpertPhone')"
          />
        </el-form-item>

        <!--    ADDEMAIL-->
        <!--    邮箱-->
        <el-form-item :label="t('admin.form.email')" prop="email">
          <el-input
            :placeholder="t('input.inputEmail')"
            v-model="form.email"
          ></el-input>
        </el-form-item>

        <!--    其他联系方式-->
        <el-form-item :label="t('admin.form.otherContact')" prop="otherContact">
          <el-input v-model="form.otherContact"></el-input>
        </el-form-item>

        <el-form-item :label="t('admin.form.location')">
          <el-input
            v-model="form.address"
            :placeholder="
              t('admin.form.placeholder', { type: t('admin.form.location') })
            "
          />
        </el-form-item>
        <!--      COMPLETED  -->
        <!-- <div class="hide_required">
          <CityOptions v-model="form" :labelWidth="100" :is_required="false" />
        </div> -->

        <div class="hide_required">
          <FieldSingle v-model="form" :labelWidth="100" />
        </div>

        <el-form-item
          :label="t('admin.form.cooperationContent')"
          prop="content"
        >
          <el-input
            v-model="form.content"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 6 }"
            :placeholder="
              t('admin.form.placeholder', {
                type: t('admin.form.cooperationDemand'),
              })
            "
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm"
            >{{ t("admin.common.confirm") }}
          </el-button>
          <el-button @click="cancel">{{ t("admin.common.cancel") }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import FieldSingle from "@/views/components/FieldSingle";

import { useI18n } from "vue-i18n";
import {
  deleteExpertWantEnterpriseByIds,
  expertWantEnterpriseList,
  insertExpertWantEnterprise,
  updateExpertWantEnterprise,
} from "@/api/admin/expert/demand";
import { ElMessage } from "element-plus";
import modal from "@/plugins/modal";
import { cloneDeep } from "lodash-es";
import { computed, reactive, ref, toRefs } from "vue";

const { t } = useI18n();

const dataList = ref([]);
const showEditDialog = ref(false);
const loading = ref(true);
// const showSearch = ref(true);
const total = ref(0);
const title = ref("");
const formRef = ref();

const data = reactive({
  form: {
    industrys: [],
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    // mode: 2,
  },
  rules: {
    enterpriseName: [
      {
        required: true,
        /*"企业名称不能为空"*/
        message: computed(() =>
          t("admin.validation.required", {
            type: t("admin.form.name", {
              type: t("admin.common.company"),
            }),
          })
        ),
        trigger: "blur",
      },
    ],
    content: [
      {
        required: true,
        /*"合作内容不能为空"*/
        message: computed(() =>
          t("admin.validation.required", {
            type: t("admin.form.cooperationContent"),
          })
        ),
        trigger: "blur",
      },
    ],
  },
});

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

/** 查询数据列表 */
const getList = async () => {
  loading.value = true;
  const resp = await expertWantEnterpriseList(queryParams.value);
  dataList.value = resp.rows;
  total.value = resp.total;
  loading.value = false;
};

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
// function resetQuery() {
//   proxy.resetForm("queryRef");
//   handleQuery();
// }
/** 删除按钮操作 */
function handleDelete(id) {
  modal
    .confirm(
      t("admin.common.confirmAction", {
        type: t("admin.common.item"),
        number: id,
        action: t("admin.common.delete"),
      })
    )
    .then(async () => {
      await deleteExpertWantEnterpriseByIds({ ids: [id] });
      getList();
      ElMessage.success(t("admin.common.deleteSuccess"));
    });
}

/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    // id: undefined,
    // name: undefined,
    // contact: undefined,
    // contact_mobile: undefined,
    industrys: [],
    // mode: 2,
    // content: undefined,
  };
  if (formRef.value) {
    formRef.value.resetFields();
  }
}

/** 添加数据 */
function handleAdd() {
  reset();
  showEditDialog.value = true;
  title.value = t("admin.form.addData");
}

/** 修改数据 */
function handleUpdate(row) {
  reset();
  form.value = cloneDeep(row);
  form.value.industrys =
    form.value.territory
      ?.split("-")
      .filter((el) => el != "")
      .map((el) => parseInt(el)) ?? [];
  showEditDialog.value = true;
  title.value = t("admin.form.editData");
}

/** 提交按钮 */
function submitForm() {
  formRef.value.validate(async (valid) => {
    form.value.territory = form.value.industrys.join("-");
    if (valid) {
      if (form.value.id) {
        await updateExpertWantEnterprise(form.value);
        ElMessage.success(t("admin.common.editSuccess"));
        showEditDialog.value = false;
        getList();
      } else {
        await insertExpertWantEnterprise(form.value);
        ElMessage.success(t("admin.common.editSuccess"));
        showEditDialog.value = false;
        getList();
      }
    }
  });
}

/** 取消按钮 */
function cancel() {
  showEditDialog.value = false;
  reset();
}

getList();
</script>
<style lang="scss" scoped>
.hide_required {
  :deep(.el-form-item__label) {
    &::before {
      display: none;
    }
  }
}
</style>
