<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryFormRef"
      v-show="showSearch"
      :inline="true"
    >
      <el-form-item label="活动名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入活动名称"
          clearable
          size="default"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属站点" prop="tenantId">
        <SiteOptions v-model="form.tenantId" :site-list="siteList" />
      </el-form-item>
      <el-form-item label="联系人" prop="contact">
        <el-input
          v-model="queryParams.contact"
          placeholder="请输入联系人"
          clearable
          size="default"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="contactMobile">
        <el-input
          v-model="queryParams.contactMobile"
          placeholder="请输入手机号码"
          clearable
          size="default"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="search"
          size="default"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="refresh" size="default" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="plus"
          size="default"
          @click="handleAdd"
          >新增</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="数据编号" prop="id" align="center" />
      <el-table-column
        label="活动名称"
        prop="title"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        label="开始时间"
        prop="beginTime"
        align="center"
        width="100"
      >
        <template #default="{ row }">
          <span>{{ row.beginTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="结束时间"
        prop="finishTime"
        align="center"
        width="100"
      >
        <template #default="{ row }">
          <span>{{ row.finishTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="截止时间"
        prop="joinDeadline"
        align="center"
        width="100"
      >
        <template #default="{ row }">
          <span>{{ row.joinDeadline }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动分类" align="center" show-overflow-tooltip>
        <template #default="{ row }"> {{ row.industry }}</template>
      </el-table-column>
      <el-table-column label="人数上限" prop="maxNumber" align="center" />
      <el-table-column label="报名费用" prop="amount" align="center" />
      <el-table-column label="已报名" prop="join_count" align="center">
        <template #default="{ row }">
          <router-link
            :to="{
              path: 'signUp',
              query: { id: row.id },
            }"
          >
            <el-link type="primary">{{ row.joinCount }}</el-link>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="站点" align="center">
        <template #default="{ row }">
          {{ siteList.find((el) => el.id === row.tenantId)?.name ?? "无" }}
        </template>
      </el-table-column>
      <el-table-column label="联系人" prop="contact" align="center" />
      <el-table-column label="手机号码" prop="contactMobile" align="center" />
      <el-table-column label="发布时间" align="center" width="100">
        <template #default="{ row }">
          <span>{{ row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="120"
        class-name="small-padding fixed-width"
      >
        <template #default="{ row }">
          <el-button
            size="small"
            type="text"
            icon="edit"
            @click="handleUpdate(row)"
            >编辑</el-button
          >
          <el-button
            size="small"
            type="text"
            icon="delete"
            @click="handleDelete(row)"
            >删除</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="35%">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="所属站点" prop="tenantId">
          <SiteOptions v-model="form.tenantId" :site-list="siteList" />
        </el-form-item>
        <el-form-item label="活动名称:" prop="title">
          <el-input v-model="form.title" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="联系人:" prop="contact">
          <el-input v-model="form.contact" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="手机号码:" prop="contactMobile">
          <el-input
            v-model="form.contactMobile"
            placeholder="请输入手机号码"
            maxlength="11"
          />
        </el-form-item>
        <el-form-item label="开始时间:" prop="beginTime">
          <el-date-picker
            value-format="yyyy-MM-dd HH:mm:ss"
            v-model="form.beginTime"
            type="datetime"
            placeholder="选择开始时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间:" prop="finishTime">
          <el-date-picker
            value-format="yyyy-MM-dd HH:mm:ss"
            v-model="form.finishTime"
            type="datetime"
            placeholder="选择结束时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="截止时间:" prop="joinDeadline">
          <el-date-picker
            value-format="yyyy-MM-dd HH:mm:ss"
            v-model="form.joinDeadline"
            type="datetime"
            placeholder="选择截止时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="地点:" required>
          <el-row type="flex" justify="space-between" :gutter="10">
            <el-col :span="8">
              <el-form-item prop="province">
                <el-select
                  v-model="form.province"
                  clearable
                  placeholder="请选择"
                  :disabled="provinceSelectList.length === 0"
                  @change="provinceChange"
                >
                  <el-option
                    v-for="item in provinceSelectList"
                    :key="item.provinceCode"
                    :label="item.provinceName"
                    :value="item.provinceCode"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="city">
                <el-select
                  v-model="form.city"
                  clearable
                  placeholder="请选择"
                  :disabled="citySelectList.length === 0"
                  @change="cityChange"
                >
                  <el-option
                    v-for="item in citySelectList"
                    :key="item.cityCode"
                    :label="item.cityName"
                    :value="item.cityCode"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="district">
                <el-select
                  v-model="form.district"
                  clearable
                  placeholder="请选择"
                  :disabled="districtSelectList.length === 0"
                >
                  <el-option
                    v-for="item in districtSelectList"
                    :key="item.areaCode"
                    :label="item.areaName"
                    :value="item.areaCode"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="详细地址:" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址" />
        </el-form-item>
        <!-- <FieldOptions v-model="form" /> -->
        <!-- <el-form-item label="活动分类:" required>
          <el-row type="flex" justify="space-between">
            <el-col :span="8">
              <el-form-item prop="industrys">
                <el-select
                  v-model="form.industrys[0]"
                  clearable
                  placeholder="请选择"
                  @change="field1Change"
                >
                  <el-option
                    v-for="item in field1SelectList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8" style="margin: 0 10px">
              <el-form-item>
                <el-select
                  v-model="form.industrys[1]"
                  clearable
                  placeholder="请选择"
                  @change="field2Change"
                >
                  <el-option
                    v-for="item in field2SelectList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item>
                <el-select
                  v-model="form.industrys[2]"
                  clearable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in field3SelectList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item> -->

        <el-form-item label="通知人群:" prop="notifyCrowd">
          <el-select v-model="form.notifyCrowd" multiple placeholder="请选择">
            <el-option
              v-for="(key, value) in identityList"
              :key="value"
              :label="key"
              :value="value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报名人数上限:" prop="maxNumber">
          <el-input
            v-model.number="form.maxNumber"
            placeholder="请输入报名人数"
          />
        </el-form-item>
        <el-form-item label="宣传图:" prop="image">
          <ImageUpload v-model="form.image" :isShowTip="false" :limit="1" />
        </el-form-item>
        <el-form-item label="活动简介:" prop="description">
          <el-input
            v-model="form.description"
            placeholder="请输入活动简介"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
          />
        </el-form-item>
        <el-form-item label="活动介绍:" prop="content">
          <WangEditor v-model="form.content" minHeight="150px" />
        </el-form-item>
        <el-form-item label="报名费用:" prop="amount">
          <el-input v-model.number="form.amount">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Active">
import {
  activityList,
  activityAdd,
  activityDetail,
  activityEdit,
  activityDelete,
} from "@/api/website/activity";
import { tenantSelect } from "@/api/subPlatform/tenant";
import {
  areaList,
  industry,
  identity,
  provinceList,
  cityList,
  districtList,
} from "@/api/config";
// import { cloneDeep } from "lodash";
import { reactive, toRefs } from "vue";
// import { constants } from "buffer";
import { ElMessage, ElMessageBox } from "element-plus";
import WangEditor from "@/components/WangEditor/index.vue";
import SiteOptions from "@/views/components/SiteOptions";

const dataList = ref([]);
const loading = ref(true);
const total = ref(0);
const showEditDialog = ref(false);
const siteList = ref([]);
const formRef = ref(null);
const queryFormRef = ref(null);
const showSearch = ref(true);
const title = ref("");
// 省市区
const provinceSelectList = ref([]);
const citySelectList = ref([]);
const districtSelectList = ref([]);
// 领域
const field1SelectList = ref([]);
const field2SelectList = ref([]);
const field3SelectList = ref([]);
// 人群类型
const identityList = ref([]);
// 表单参数
const data = reactive({
  queryParams: {
    title: undefined,
    tenantId: undefined,
    contact: undefined,
    contactMobile: undefined,
    pageNum: 1,
    pageSize: 10,
  },
  form: {
    industrys: [],
  },
  rules: {
    title: [{ required: true, message: "活动名称不能为空", trigger: "blur" }],
    contact: [{ required: true, message: "联系人不能为空", trigger: "blur" }],
    contactMobile: [
      { required: true, message: "手机号码不能为空", trigger: "blur" },
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: ["blur", "change"],
      },
    ],
    tenantId: [
      {
        required: true,
        message: "所属站点不能为空",
        trigger: ["blur", "change"],
      },
    ],
    beginTime: [
      { required: true, message: "开始时间不能为空", trigger: "change" },
    ],
    finishTime: [
      { required: true, message: "结束时间不能为空", trigger: "change" },
    ],
    joinDeadline: [
      { required: true, message: "截止时间不能为空", trigger: "change" },
    ],
    province: [{ required: true, message: "请选择", trigger: "change" }],
    city: [{ required: true, message: "请选择", trigger: "change" }],
    district: [{ required: true, message: "请选择", trigger: "change" }],
    address: [{ required: true, message: "详细地址不能为空", trigger: "blur" }],
    industrys: [
      {
        type: "array",
        required: true,
        message: "请选择",
        trigger: "change",
      },
    ],
    notifyCrowd: [
      {
        type: "array",
        required: true,
        message: "请选择",
        trigger: "change",
      },
    ],
    maxNumber: [
      { required: true, message: "报名人数不能为空", trigger: "blur" },
    ],
    image: [{ required: true, message: "请上传宣传图", trigger: "blur" }],
    description: [
      { required: true, message: "活动简介不能为空", trigger: "blur" },
    ],
    content: [{ required: true, message: "活动介绍不能为空", trigger: "blur" }],
    amount: [{ required: true, message: "报名费用不能为空", trigger: "blur" }],
  },
});
const { queryParams, form, rules } = toRefs(data);

const resetQuery = () => {
  if (queryFormRef.value) {
    queryFormRef.value.resetFields();
  }
  handleQuery();
};
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
const getList = async () => {
  loading.value = true;
  const resp = await activityList(queryParams.value);
  dataList.value = resp.rows;
  total.value = resp.total;
  loading.value = false;
};

// 获取站点列表
const getSiteList = async () => {
  const resp = await tenantSelect();
  siteList.value = resp.rows;
};
// 取消按钮
const cancel = () => {
  showEditDialog.value = false;
  // this.memberOpen = false;
  reset();
};
// 表单重置
const reset = () => {
  form.value = {
    id: undefined,
    tenantId: undefined,
    title: undefined,
    industrys: [],
    notifyCrowd: [],
    maxNumber: 0,
    isHome: 1,
  };
  if (formRef.value) {
    formRef.value.resetFields();
  }
};
const handleAdd = () => {
  // getProvinceList();
  reset();
  showEditDialog.value = true;
  title.value = "新增";
};

// 获取省列表
const getProvinceList = async () => {
  const { data } = await provinceList();
  provinceSelectList.value = data;
};
// 根据省id获取地级市列表
const getCityListByProvinceId = async (provinceId) => {
  const { data } = await cityList(provinceId);
  citySelectList.value = data;
};
// 根据市id获取县区列表
const getAreaListByCityId = async (cityId) => {
  const { data } = await districtList(cityId);
  districtSelectList.value = data;
};

// 当修改province时，或清除province时
const provinceChange = () => {
  // 清除市县代码列表
  form.value.city = undefined;
  form.value.district = undefined;
  // 清除市县列表
  citySelectList.value = [];
  districtSelectList.value = [];
  // 重新请求城市列表
  form.value.province && getCityListByProvinceId(form.value.province);
};
const cityChange = () => {
  // 清除县区代码列表
  form.value.district = undefined;
  districtSelectList.value = [];
  form.value.city && getAreaListByCityId(form.value.city);
};

const getFieldByParent = (id) => {
  return new Promise((resolve, reject) => {
    industry({ parent_id: id })
      .then(({ code, msg, data }) => {
        if (code == 200) {
          resolve(data);
        } else {
          ElMessage.error(msg);
          reject({ msg, code });
        }
      })
      .catch((error) => {
        reject(error);
      });
  });
};
const field1Change = async (id) => {
  delete form.value.industrys[1];
  delete form.value.industrys[2];
  if (!id) {
    field2SelectList.value = [];
    field3SelectList.value = [];
    return false;
  }
  field2SelectList.value = await getFieldByParent(id);
};
const field2Change = async (id) => {
  delete form.value.industrys[2];
  if (!id) {
    field3SelectList.value = [];
    return false;
  }
  field3SelectList.value = await getFieldByParent(id);
};

const handleUpdate = async (row) => {
  reset();
  const resp = await activityDetail(row.id);
  const formData = resp.data;
  form.value = formData;
  showEditDialog.value = true;
  title.value = "修改";
};
const submitForm = () => {
  // let notifys = 0;
  // form.value.notifyCrowd.map((item) => {
  //   notifys = notifys | (item - 0);
  // });
  // let formData = cloneDeep(form.value);
  // formData.notifyCrowd = notifys;
  // formData.industrys = [form.value.industrys.join("-")];
  this.$refs["form"].validate((valid) => {
    if (valid) {
      if (formData.id != undefined) {
        activityEdit(formData).then((response) => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      } else {
        activityAdd(formData).then((response) => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      }
    }
  });
};
/** 删除按钮操作 */
const handleDelete = (row) => {
  ElMessageBox.confirm(`是否确认删除名为${row.title}的数据项？`)
    .then(async () => {
      await activityDelete(row.id);
      getList();
      ElMessage.success("删除成功");
    })
    .catch(() => {});
};

getList();
getSiteList();
getProvinceList();
</script>

<!-- <script>
export default {
  data() {
    return {
      is_super: this.$store.getters.is_super,
      loading: true,
      showSearch: true,

      total: 0,
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 省市区
      provinceSelectList: [],
      citySelectList: [],
      districtSelectList: [],
      // 领域
      field1SelectList: [],
      field2SelectList: [],
      field3SelectList: [],
      // 人群类型
      identityList: [],
      // 表单参数
    };
  },
  methods: {
    
  },
  created() {
    this.getList();
    areaList().then((res) => {
      this.provinceSelectList = res.data;
    });
    industry().then((res) => {
      this.field1SelectList = res.data;
    });
    identity().then((res) => {
      this.identityList = res.data;
    });
  },
};
</script> -->
