<template>
  <div class="management">
    <basic-container>
      <avue-crud
        ref="crud"
        :page="page"
        :table-loading="tableLoading"
        :option="tableOption"
        :data="tableData"
        v-model="form"
        @on-load="getList"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @size-change="sizeChange"
        @current-change="currentChange"
        @selection-change="selectionChange"
      >
        <template slot="menuLeft">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="small"
            @click="batchFn"
            >批量</el-button
          >
        </template>
        <template slot="menu" slot-scope="scope">
          <el-button type="text" size="small" @click="assignmentFn(scope.row)"
            >分配</el-button
          >
          <el-button type="text" size="small" @click="renewalFn(scope.row)"
            >续期</el-button
          >
        </template>
      </avue-crud>
    </basic-container>

    <!-- 分配 -->
    <el-dialog
      title="企业管理"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="handleClose"
    >
      <el-form :model="form" ref="form" label-width="80px">
        <el-form-item label="企业名称" prop="name">
          <el-input
            type="textarea"
            v-model="form.name"
            resize="none"
            disabled
          />
        </el-form-item>
        <el-form-item label="企业类型" prop="levelName" v-if="showInfo">
          <el-input v-model="form.levelName" disabled />
        </el-form-item>
        <el-form-item label="上级企业" prop="superDeptName" v-if="showInfo">
          <el-input v-model="form.superDeptName" disabled />
        </el-form-item>
        <el-form-item label="负责人" prop="userIds">
          <el-select
            v-model="form.userIds"
            multiple
            placeholder="请选择"
            class="w100"
          >
            <el-option
              v-for="item in csmList"
              :key="item.userId"
              :label="item.realname"
              :value="item.userId"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="saveFn">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { tableOption } from "@/const/crud/bcpages/management.js";
import {
  fetchList,
  expiryDateApi,
  gerCsmListApi,
  assignCmsToDeptApi
} from "@/api/bcpages/management.js";
export default {
  data() {
    return {
      showInfo: false,
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      tableData: [],
      tableOption: tableOption,
      tableLoading: false,
      form: {},
      currentRow: {},
      dialogVisible: false,
      csmList: [],
      form: {
        name: "",
        levelName: "",
        superDeptName: "",
        userIds: []
      },

      selection: []
    };
  },
  created() {
    this.getCsmList();
  },
  methods: {
    async getCsmList() {
      const res = await gerCsmListApi();
      this.csmList = res.data.data;
    },
    async getList(page, params) {
      this.tableLoading = true;
      const obj = Object.assign(
        {
          current: page.currentPage,
          size: page.pageSize
        },
        params,
        this.searchForm
      );
      const res = await fetchList(obj);
      this.page.total = res.data.data.total;
      this.tableData = res.data.data.records;
      this.tableLoading = false;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    currentChange(current) {
      this.page.currentPage = current;
    },
    searchChange(form, done) {
      this.searchForm = form;
      this.page.currentPage = 1;
      this.getList(this.page, form);
      done();
    },
    refreshChange() {
      this.getList(this.page);
    },
    batchFn() {
      if (!this.selection.length) {
        return this.$message.info("请先选择数据");
      }
      const names = this.selection.map(item => item.name).join("，");
      this.form.name = names;
      this.showInfo = false;
      this.dialogVisible = true;
    },
    assignmentFn(row) {
      this.currentRow = row;
      this.form.name = row.name;
      this.form.levelName = row.levelName;
      this.form.superDeptName = row.superDeptName;
      if (row.csmUserIds) {
        this.form.userIds = row.csmUserIds;
      }
      this.showInfo = true;
      this.dialogVisible = true;
    },
    selectionChange(list) {
      this.selection = list;
    },
    handleClose() {
      this.currentRow = {};
      this.selection = [];
      this.$refs.form.resetFields();
      this.form.userIds = [];
      this.dialogVisible = false;
    },
    saveFn() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          let deptIds = [];
          if (this.currentRow) {
            deptIds = [this.currentRow.deptId];
          }
          if (this.selection.length) {
            deptIds = this.selection.map(item => item.deptId);
          }
          const obj = {
            deptIds,
            userIds: this.form.userIds
          };
          const res = await assignCmsToDeptApi(obj);
          if (res.data.code === 0) {
            this.$message.success("负责人添加成功");
            this.handleClose();
            this.getList(this.page);
          }
        } else {
          return false;
        }
      });
    },
    getOneYearLater(expiryDate) {
      // 获取当前日期
      let currentDate = expiryDate ? new Date(expiryDate) : new Date();
      // 获取一年后的日期
      const oneYearLater = new Date();
      oneYearLater.setFullYear(currentDate.getFullYear() + 1);
      // 提取年、月、日
      const year = oneYearLater.getFullYear();
      const month = oneYearLater.getMonth() + 1; // 月份是从 0 开始的，所以要加1
      const day = oneYearLater.getDate();
      // 格式化输出
      const formattedDate = year + "年" + month + "月" + day + "日";
      return formattedDate;
    },
    renewalFn(row) {
      const oneYearLater = this.getOneYearLater(row.expiryDate);
      this.$confirm(`确认将企业的服务截止时间延长至：${oneYearLater}`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const obj = {
            deptIds: [row.deptId]
          };
          const res = await expiryDateApi(obj);
          if (res.data.code === 0) {
            this.$Message.success("续期成功");
            this.getList(this.page);
          }
        })
        .catch(() => {});
    }
  }
};
</script>

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