<script setup>
import { computed, reactive, ref, toRefs } from "vue";
import FieldSingle from "@/views/components/FieldSingle";
import dayjs from "dayjs";
import {
  deleteBrokerEnterprise,
  insertBrokerEnterprise,
  listBrokerEnterprise,
} from "@/api/admin/agent/service/enterprise";
import { ElMessage } from "element-plus";
import modal from "@/plugins/modal";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const router = useRouter();
const dataList = ref([]);
const loading = ref(true);
const total = ref(0);
const showSearch = ref(true);
const showDialog = ref(false);
const queryRef = ref();
const fieldRef = ref();
const formRef = ref();
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    enterpriseName: null,
  },
  form: {},
  rules: {
    enterpriseName: [
      {
        required: true,
        message: computed(() =>
          t("admin.form.placeholder", {
            type: t("admin.common.company"),
          })
        ),
        trigger: "blur",
      },
    ],
  },
});
const { queryParams, form, rules } = toRefs(data);

const getList = async () => {
  loading.value = true;
  const resp = await listBrokerEnterprise(queryParams.value);
  dataList.value = resp.rows;
  total.value = resp.total;
  loading.value = false;
};

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

/** 重置按钮操作 */
const resetQuery = () => {
  if (queryRef.value) {
    queryRef.value.resetFields();
    handleQuery();
  }
};

const reset = () => {
  form.value = {
    enterpriseName: null,
    industrys: [],
  };
  formRef.value?.resetFields();
};
const handleAdd = () => {
  reset();
  showDialog.value = true;
};

const submitForm = async () => {
  formRef.value.validate(async (valid) => {
    const fieldValid = await fieldRef.value.validateForm();
    if (valid && fieldValid) {
      if (form.value.id) {
        /*TODO edit*/
      } else {
        /*TODO add*/
        insertBrokerEnterprise(form.value).then(() => {
          ElMessage.success(t("admin.common.addSuccess"));
          showDialog.value = false;
          getList();
        });
      }
    } else {
      console.log("validation failed");
    }
  });
};
const cancel = () => {
  reset();
  showDialog.value = false;
};

function handleDelete(id) {
  modal
    .confirm(
      t("admin.common.confirmAction", {
        action: t("admin.common.delete"),
        number: id,
        type: t("admin.common.company"),
      })
    )
    .then(() => {
      return deleteBrokerEnterprise(id);
    })
    .then(() => {
      getList();
      ElMessage.success(t("admin.common.deleteSuccess"));
    })
    .catch((err) => {
      console.log(err);
    });
}

/**
 * go to 技术需求列表
 * @param id
 */
const handleTechDemand = (id) => {
  router.push({
    path: "/admin/service/technology-demand",
    query: {
      id,
    },
  });
};

getList();
</script>

<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryRef"
      :inline="true"
      :model="queryParams"
      @submit.prevent
    >
      <el-form-item
        :label="t('admin.form.name', { type: t('admin.common.company') })"
        prop="enterpriseName"
      >
        <el-input
          v-model="queryParams.enterpriseName"
          clearable
          :placeholder="
            t('admin.form.placeholder', { type: t('admin.common.company') })
          "
          @keyup.enter.prevent="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button icon="Search" type="primary" @click="handleQuery">
          {{ t("admin.common.search") }}
        </el-button>
        <el-button icon="Refresh" @click="resetQuery">
          {{ t("admin.common.reset") }}
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10">
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table :data="dataList">
      <el-table-column
        align="center"
        :label="t('admin.form.name', { type: t('admin.common.company') })"
        prop="enterpriseName"
      />
      <el-table-column
        align="center"
        :label="t('admin.form.industry')"
        prop="industryStr"
      />
      <el-table-column
        align="center"
        :label="t('quantityOverview.demand')"
        prop="demandCount"
      />
      <el-table-column
        align="center"
        :label="t('admin.table.serviceDemandCount')"
        prop="runDemandCount"
      />
      <el-table-column
        align="center"
        :label="t('admin.table.finishedDemandCount')"
        prop="completeDemandCount"
      />
      <el-table-column align="center" :label="t('admin.table.addTime')">
        <template #default="{ row }">
          {{ dayjs(row.createTime).format("YYYY-MM-DD HH:mm:ss") }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="">
        <template #default="{ row }">
          <el-button
            link
            type="text"
            @click="handleTechDemand(row.enterpriseId)"
            >{{
              t("admin.table.managementOf", {
                type: t("routes.company.technicalDemand"),
              })
            }}
          </el-button>
<!--          <el-button link type="text">-->
<!--            {{-->
<!--              t("admin.table.managementOf", {-->
<!--                type: t("admin.common.achievement"),-->
<!--              })-->
<!--            }}-->
<!--          </el-button>-->
          <el-button link type="text" @click="handleDelete(row.id)">
            {{ t("admin.common.delete") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <el-dialog v-model="showDialog" append-to-body width="800px">
      <el-form ref="formRef" :label-width="120" :model="form" :rules="rules">
        <el-form-item
          :label="t('admin.form.name', { type: t('admin.common.company') })"
          prop="enterpriseName"
        >
          <el-input v-model="form.enterpriseName" />
        </el-form-item>
        <field-single ref="fieldRef" v-model="form" />
      </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>

<style lang="scss" scoped></style>
