<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="开户主体名称" prop="advertiserName">
        <el-input
          v-model="queryParams.advertiserName"
          placeholder="请输入广告主开户主体名称"
          clearable
          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"
      v-if="
        $store.getters.roles[0] == 'operationsManager' ||
        $store.getters.roles[0] == 'directorOperations' ||
        $store.getters.roles[0] == 'admin'
      "
    >
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-document-add"
          size="mini"
          @click="handleAdd"
          >新增广告主</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="typeList"
      @selection-change="handleSelectionChange"
      ref="multipleTable"
    >
      <el-table-column label="广告主开户主体名称" align="center" prop="advertiserName">
        <template slot-scope="scope">
          <a style="color: #409eff; display: block" @click="toProjectList(scope.row)">{{
            scope.row.advertiserName
          }}</a>
        </template>
      </el-table-column>
      <el-table-column label="联系人" align="center" prop="userName" />
      <el-table-column label="联系方式" align="center" prop="mobile">
        <template slot-scope="scope">
          {{ scope.row.mobile ? scope.row.mobile : "-" }}
        </template>
      </el-table-column>
      <el-table-column label="联系邮箱" align="center" prop="email" />
      <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" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="创建人" prop="createBy">
          {{ $store.getters.name }}
        </el-form-item>
        <el-form-item label="广告主开户主体名称" prop="advertiserName">
          <el-input
            v-model="form.advertiserName"
            placeholder="请输入广告主开户主体名称"
            clearable
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="负责人" prop="userId">
          <el-select
            v-model="form.userId"
            placeholder="选择负责人"
            clearable
            style="width: 240px"
            filterable
          >
            <el-option
              v-for="item in formList.personList"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式" prop="mobile">
          <el-input
            placeholder="请输入联系方式"
            style="width: 240px"
            v-model="form.mobile"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="联系邮箱" prop="email">
          <el-input
            placeholder="请输入联系邮箱"
            style="width: 240px"
            v-model="form.email"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="confirmLoading"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAdvertiserList,
  addAdvertiser,
  editAdvertiser,
  deleteById,
} from "@/api/accountManagement/accountManagement";
import { listUser } from "@/api/system/user";
export default {
  name: "AccountManagement",
  data() {
    let validatePhone = (rule, value, callback) => {
      /*console.log(rule);
      console.log(value);
      console.log(callback);*/
      if (!value) {
        callback(new Error("联系方式不能为空！"));
      }
      //使用正则表达式进行验证手机号码
      if (!/^1[3456789]\d{9}$/.test(value)) {
        callback(new Error("手机号不正确！"));
      }
      callback();
    };
    var checkEmail = (rules, value, callback) => {
      if (!value) {
        callback(new Error("邮箱不能为空！"));
      } else {
        // 验证邮箱的正则表达式
        const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
        if (regEmail.test(value)) {
          return callback();
        }
        callback(new Error("请输入合法的邮箱"));
      }
    };

    return {
      dialogTableVisible: false,
      logPage: {
        pageNum: 1,
        pageSize: 10,
      },
      logData: [],
      logTotal: 0,
      logLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 编辑所用id
      updateId: null,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      typeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 分配销售
      openAllocation: false,
      // 选择的销售id
      saleId: undefined,
      // 获取用户id
      userId: undefined,
      // 销售列表
      saleList: [],
      // 分配销售确定loading
      confirmLoadingSale: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        advertiserName: undefined,
      },
      //查询参数所用下拉数据
      queryParamsList: {},
      // 表单参数
      form: {},
      //上传报表下拉数据
      formList: {
        personList: [], //新增下拉人员列表
      },
      fileList: [],
      //获取销售线索文件流
      dateFile: null,
      //销售线索上传loading
      confirmLoading: false,
      // 表单校验
      rules: {
        advertiserName: [
          { required: true, message: "广告主开户主体名称必填", trigger: "blur" },
        ],
        userId: [{ required: true, message: "请选择负责人", trigger: "change" }],
        mobile: {
          required: true,
          // message: "联系方式必填",
          validator: validatePhone,
          trigger: "blur",
        },
        email: {
          required: true,
          // message: "联系方式必填",
          validator: checkEmail,
          trigger: "blur",
        },
      },
    };
  },
  created() {
    this.userId = this.$store.getters.userId;
  },
  mounted() {
    this.$nextTick(() => {
      this.getList();
      this.listUser();
    });
  },
  methods: {
    listUser() {
      listUser({ pageNum: 1, pageSize: 10000 }).then((res) => {
        this.formList.personList = res.rows;
      });
    },
    /** 复选框禁用 */
    selectable(row, index) {
      return true;
      // if (!!row.saleName) {
      //   return false;
      // } else {
      //   return true;
      // }
    },
    toProjectList(item) {
      this.$router.replace({
        path: "/account/projectList",
        query: {
          id: item.id,
          name: item.advertiserName,
        },
      });
    },
    /** 查询字典类型列表 */
    getList() {
      this.loading = true;
      getAdvertiserList(this.queryParams).then((response) => {
        this.typeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.confirmLoading = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.dateFile = null;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.pageNum = 1;
      // this.handleQuery();
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新建广告主";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
    },

    handleUpdate(item) {
      this.reset();
      this.open = true;
      this.title = "修改广告主";
      this.$nextTick(() => {
        this.updateId = item.id;
        this.$set(this.form, "advertiserName", item.advertiserName);
        this.$set(this.form, "userId", item.userId);
        this.$set(this.form, "mobile", item.mobile);
        this.$set(this.form, "email", item.email);
      });
    },
    /** 删除按钮 */
    handleDelete(item) {
      this.$modal
        .confirm(`请确认是否删除此广告主？`)
        .then(() => {
          var params = {};
          params.id = item.id;
          params.userId = this.$store.getters.userId;
          deleteById(params)
            .then((res) => {
              this.$modal.msgSuccess("删除成功");
              this.resetQuery();
            })
            .catch(() => {
              this.$message.error("失败");
              this.loading = false;
            });
        })
        .catch(() => {});
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          var params = { ...this.form };
          params.createBy = this.userId;
          if (!!this.updateId) {
            editAdvertiser({ ...params, id: this.updateId }).then((res) => {
              this.open = false;
              this.confirmLoading = false;
              this.resetQuery();
            });
          } else {
            addAdvertiser(params).then((res) => {
              this.open = false;
              this.confirmLoading = false;
              this.resetQuery();
            });
          }
        }
      });
    },
  },
};
</script>
