<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      v-show="showSearch"
      :inline="true"
    >
      <el-form-item label="活动名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入活动名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属站点" prop="tenant_id" v-if="is_super">
        <SiteOptions v-model="queryParams" />
      </el-form-item>
      <el-form-item label="联系人" prop="contact">
        <el-input
          v-model="queryParams.contact"
          placeholder="请输入联系人"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="contact_mobile">
        <el-input
          v-model="queryParams.contact_mobile"
          placeholder="请输入手机号码"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @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="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="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="begin_at"
        align="center"
        width="100"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.begin_at) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="结束时间"
        prop="finish_at"
        align="center"
        width="100"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.finish_at) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="截止时间"
        prop="join_deadline"
        align="center"
        width="100"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.join_deadline) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="活动分类"
        prop="industry"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column label="人数上限" prop="max_number" align="center" />
      <el-table-column label="报名费用" prop="amount" align="center" />
      <el-table-column label="已报名" prop="join_count" align="center">
        <template slot-scope="scope">
          <router-link
            :to="{
              path: 'signUp',
              query: { id: scope.row.id },
            }"
          >
            <el-link type="primary">{{ scope.row.join_count }}</el-link>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="站点" prop="area" align="center" />
      <el-table-column label="联系人" prop="contact" align="center" />
      <el-table-column label="手机号码" prop="contact_mobile" align="center" />
      <el-table-column
        label="发布时间"
        prop="created_at"
        align="center"
        width="100"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.created_at) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page_num"
      :limit.sync="queryParams.page_size"
      @pagination="getList"
    />
    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="35%">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="所属站点" prop="tenant_id">
          <SiteOptions v-model="form" />
        </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="contact_mobile">
          <el-input
            v-model="form.contact_mobile"
            placeholder="请输入手机号码"
            maxlength="11"
          />
        </el-form-item>
        <el-form-item label="开始时间:" prop="begin_at">
          <el-date-picker
            value-format="yyyy-MM-dd HH:mm:ss"
            v-model="form.begin_at"
            type="datetime"
            placeholder="选择开始时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间:" prop="finish_at">
          <el-date-picker
            value-format="yyyy-MM-dd HH:mm:ss"
            v-model="form.finish_at"
            type="datetime"
            placeholder="选择结束时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="截止时间:" prop="join_deadline">
          <el-date-picker
            value-format="yyyy-MM-dd HH:mm:ss"
            v-model="form.join_deadline"
            type="datetime"
            placeholder="选择截止时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="地点:" required>
          <el-row type="flex" justify="space-between">
            <el-col :span="8">
              <el-form-item prop="province">
                <el-select
                  v-model="form.province"
                  clearable
                  placeholder="请选择"
                  @change="provinceCodeChange"
                >
                  <el-option
                    v-for="(key, value) in provinceSelectList"
                    :key="value"
                    :label="key"
                    :value="value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8" style="margin: 0 10px">
              <el-form-item prop="city">
                <el-select
                  v-model="form.city"
                  clearable
                  placeholder="请选择"
                  @change="cityCodeChange"
                >
                  <el-option
                    v-for="(key, value) in citySelectList"
                    :key="key"
                    :label="key"
                    :value="value"
                  >
                  </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="请选择"
                >
                  <el-option
                    v-for="(key, value) in districtSelectList"
                    :key="value"
                    :label="key"
                    :value="value"
                  >
                  </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>
        <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="notify_crowd">
          <el-select v-model="form.notify_crowd" 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="max_number">
          <el-input
            v-model.number="form.max_number"
            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="is_home">
          <el-radio-group v-model="form.is_home">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="活动简介:" prop="description">
          <el-input
            v-model.number="form.description"
            placeholder="请输入活动简介"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
          />
        </el-form-item>
        <el-form-item label="活动介绍:" prop="content">
          <Editor v-model="form.content" :minHeight="150" />
        </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>
import {
  activityList,
  activityAdd,
  activityDetail,
  activityEdit,
  activityDelete,
} from "@/api/website/activity";
import { areaList, industry, identity } from "@/api/config";
export default {
  data() {
    return {
      is_super: this.$store.getters.is_super,
      loading: true,
      showSearch: true,
      queryParams: {
        title: undefined,
        tenant_id: undefined,
        contact: undefined,
        contact_mobile: undefined,
        page_num: 1,
        page_size: 10,
      },
      total: 0,
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 省市区
      provinceSelectList: [],
      citySelectList: [],
      districtSelectList: [],
      // 领域
      field1SelectList: [],
      field2SelectList: [],
      field3SelectList: [],
      // 人群类型
      identityList: [],
      // 表单参数
      form: {
        industrys: [],
      },
      rules: {
        title: [
          { required: true, message: "活动名称不能为空", trigger: "blur" },
        ],
        contact: [
          { required: true, message: "联系人不能为空", trigger: "blur" },
        ],
        contact_mobile: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: ["blur", "change"],
          },
        ],
        tenant_id: [
          {
            required: true,
            message: "所属站点不能为空",
            trigger: ["blur", "change"],
          },
        ],
        begin_at: [
          { required: true, message: "开始时间不能为空", trigger: "change" },
        ],
        finish_at: [
          { required: true, message: "结束时间不能为空", trigger: "change" },
        ],
        join_deadline: [
          { 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",
          },
        ],
        notify_crowd: [
          {
            type: "array",
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],
        max_number: [
          { 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" },
        ],
      },
    };
  },
  methods: {
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleQuery() {
      this.queryParams.page_num = 1;
      this.getList();
    },
    getList() {
      this.loading = true;
      activityList(this.queryParams).then((res) => {
        this.dataList = res.data.data;
        this.total = res.data.count;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.memberOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        tenant_id: undefined,
        title: undefined,
        industrys: [],
        notify_crowd: [],
        max_number: 0,
        is_home: 1,
      };
      this.resetForm("form");
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增";
    },
    getProvinceByParent(id) {
      return new Promise((resolve, reject) => {
        areaList({ code: id })
          .then(({ code, msg, data }) => {
            if (code == 200) {
              resolve(data);
            } else {
              this.$message.error(msg);
              reject({ msg, code });
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    async provinceCodeChange(id) {
      delete this.form.city;
      delete this.form.district;
      if (!id) {
        this.citySelectList = [];
        this.districtSelectList = [];
        return false;
      }
      this.citySelectList = await this.getProvinceByParent(id);
    },
    async cityCodeChange(id) {
      delete this.form.district;
      if (!id) {
        this.districtSelectList = [];
        return false;
      }
      this.districtSelectList = await this.getProvinceByParent(id);
    },

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

    handleUpdate(row) {
      this.reset();
      activityDetail({ id: row.id }).then((res) => {
        const formData = res.data;
        this.provinceCodeChange(res.data.province);
        this.cityCodeChange(res.data.city);
        let arr = [];
        for (const key in this.identityList) {
          if (Object.hasOwnProperty.call(this.identityList, key)) {
            if (((key - 0) & formData.notify_crowd) > 0) {
              arr.push(key);
            }
          }
        }
        formData.industrys = formData.industrys[0].split("-");
        if (formData.industrys.length == 2) {
          this.field1Change(formData.industrys[0]);
        } else if (formData.industrys.length == 3) {
          this.field1Change(formData.industrys[0]);
          this.field2Change(formData.industrys[1]);
        }
        formData.notify_crowd = arr;
        this.form = formData;
        this.open = true;
        this.title = "修改";
      });
    },
    submitForm() {
      let notifys = 0;
      this.form.notify_crowd.map((item) => {
        notifys = notifys | (item - 0);
      });
      let formData = Object.assign({}, this.form);
      formData.notify_crowd = notifys;
      formData.industrys = [this.form.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();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除名为"' + row.title + '"的数据项？')
        .then(function () {
          return activityDelete({ id: row.id });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
  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>