<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="账户ID" prop="accountId">
        <el-input
          v-model="queryParams.accountId"
          placeholder="请输入账户ID"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="账户名称" prop="accountName">
        <el-input
          v-model="queryParams.accountName"
          placeholder="请输入账户名称"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="运营名称" prop="operatorName">
        <el-input
          v-model="queryParams.operatorName"
          placeholder="请输入运营名称"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          style="width: 240px"
        />
      </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-table
      v-loading="loading"
      :data="typeList"
      @selection-change="handleSelectionChange"
      ref="multipleTable"
    >
      <el-table-column
        label="账户所属人"
        align="center"
        prop="operatorName"
        width="200px"
      />
      <el-table-column label="项目名称" align="center" prop="projectName" width="200px" />
      <el-table-column label="账户ID" align="center" prop="accountId" width="200px" />
      <el-table-column label="账户名称" align="center" prop="accountName" width="200px" />
      <el-table-column label="媒体" align="center" prop="mediaCode">
        <template slot-scope="scope">
          <div v-if="scope.row.mediaCode">
            {{ scope.row.mediaCode | mediaName }}
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column label="账户状态" align="center" prop="accountStatus" width="200px">
        <template slot-scope="scope">
          <div v-if="scope.row.accountStatus">
            <el-switch
              v-model="scope.row.accountStatusShow"
              @change="changeStatus($event, scope.row)"
            >
            </el-switch>
            <!-- {{ scope.row.accountStatus == 1 ? "有效" : "失效" }} -->
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="getAccount(scope.row)"
            >转移账户</el-button
          >
          <el-button
            size="mini"
            type="text"
            :disabled="
              $store.getters.roles[0] == 'admin' ? false : userId != scope.row.operatorId
            "
            @click="cancelAccount(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="180px">
        <el-form-item label="转户人" prop="transferor">
          {{ personName }}
        </el-form-item>

        <el-form-item label="受让人" prop="assignee">
          <el-select
            ref="optionAdvertiser"
            v-model="form.assignee"
            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="transferorDate">
          <el-date-picker
            v-model="form.transferorDate"
            value-format="yyyy-MM-dd"
            type="date"
            style="width: 240px"
            placeholder="选择日期"
            @change="getTomorrow"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="受让人绩效统计开始日期" prop="assigneeDate">
          {{ form.assigneeDate }}
        </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 {
  getAccountList,
  getMyProjects,
  getUnboundAccountList,
  claimAccount,
  accountDeleteById,
  addTransferAccount,
  editAccountStatus,
  getAccountByProjectId,
  deleteClaimAccount,
} from "@/api/accountManagement/accountManagement";
import { listUser } from "@/api/system/user";
import { ifError } from "assert";
export default {
  name: "MyAccount",
  data() {
    return {
      dialogTableVisible: false,
      logPage: {
        pageNum: 1,
        pageSize: 10,
      },
      logData: [],
      logTotal: 0,
      logLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      accountId: undefined,
      projectId: undefined,
      personId: undefined,
      personName: undefined,
      // 编辑所用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,
        accountId: undefined,
        ksId: undefined,
        accountName: undefined,
        operatorName: undefined,
        projectName: undefined,
      },
      //查询参数所用下拉数据
      queryParamsList: {
        statusList: [
          { value: 1, label: "认领" },
          { value: 2, label: "未认领" },
        ],
      },
      // 表单参数
      form: {
        ocpxActionTypeList: [],
      },
      //上传报表下拉数据
      formList: {
        personList: [], //新增下拉人员列表
        projectList: [], //项目列表
      },
      fileList: [],
      //获取销售线索文件流
      dateFile: null,
      //销售线索上传loading
      confirmLoading: false,
      // 表单校验
      rules: {
        assignee: [{ required: true, message: "受让人必选", trigger: "change" }],
        transferorDate: [
          { required: true, message: "转户人绩效截至日期必填", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.userId = this.$store.getters.userId;
  },
  filters: {
    ocpxActionTypeName(status) {
      const statusMap = {
        72: "涨粉",
        395: "订单支付",
        192: "直播推广 ROI",
      };
      return statusMap[status];
    },
    mediaName(status) {
      const statusMap = {
        JN: "磁力金牛",
      };
      return statusMap[status];
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.getList();
    });
  },
  methods: {
    listUser() {
      listUser({ pageNum: 1, pageSize: 10000 }).then((res) => {
        this.formList.personList = res.rows;
      });
    },
    getProject() {
      getMyProjects({ pageNum: 1, pageSize: 10000, userId: this.userId }).then((res) => {
        this.formList.projectList = res.rows;
      });
    },
    /** 复选框禁用 */
    selectable(row, index) {
      return true;
    },

    /** 查询字典类型列表 */
    getList() {
      this.loading = true;
      getAccountList({ ...this.queryParams, userId: this.userId }).then((response) => {
        this.typeList = response.rows.map((item) => {
          return {
            ...item,
            accountStatusShow: item.accountStatus == 1 ? true : false,
          };
        });
        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();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
    },
    changeStatus(value, item) {
      editAccountStatus({ accountStatus: value ? 1 : 2, id: item.id }).then((res) => {
        this.$message.success("状态修改成功");
      });
    },
    getAccount(item) {
      //   getAccountByProjectId({ projectId: item.id }).then((res) => {});
      this.open = true;
      this.title = "账户转让";
      this.listUser();
      this.accountId = item.accountId;
      this.projectId = item.projectId;
      this.personId = item.operatorId;
      this.personName = item.operatorName;
      this.reset();
      this.$nextTick(() => {
        this.$refs["form"].clearValidate("assignee");
      });
    },

    cancelAccount(item) {
      this.$modal
        .confirm(`请确认是否删除此项目？`)
        .then(() => {
          var params = {};
          params.accountId = item.accountId;
          params.userId = this.$store.getters.userId;
          deleteClaimAccount(params)
            .then((res) => {
              this.$modal.msgSuccess("删除成功");
              this.resetQuery();
            })
            .catch(() => {
              this.$message.error("失败");
              this.loading = false;
            });
        })
        .catch(() => {});
    },
    getTomorrow(value) {
      console.log(value);
      if (value) {
        const date = new Date(value);
        date.setTime(date.getTime() + 3600 * 1000 * 24);

        let y = date.getFullYear();
        let MM = date.getMonth() + 1;
        MM = MM < 10 ? "0" + MM : MM;
        let dd = date.getDate();
        dd = dd < 10 ? "0" + dd : dd;
        this.$set(this.form, "assigneeDate", `${y}-${MM}-${dd}`);
      } else {
        this.$set(this.form, "assigneeDate", "-");
      }
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          var params = { ...this.form };
          params.accountId = this.accountId;
          params.projectId = this.projectId;
          params.transferor = this.personId;
          params.userId = this.userId;

          console.log(params);

          addTransferAccount({ ...params }).then((res) => {
            this.open = false;
            this.confirmLoading = false;
            this.resetQuery();
          });
        }
      });
    },
  },
};
</script>
