<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <div class="filter-container">
      <!-- 系统选择框 -->
      <el-select
        v-model="listQuery.sysOrigin"
        placeholder="系统"
        style="width: 120px"
        class="filter-item"
        @change="changeSysOrigin"
      >
        <el-option
          v-for="item in permissionsSysOriginPlatforms"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
          <span style="float: left;">
            <sys-origin-icon :icon="item.value" :desc="item.value"
          /></span>
          <span style="float: left;margin-left:10px">{{ item.label }}</span>
        </el-option>
      </el-select>

      <!-- 区域选择框 -->
      <el-select
        v-model="listQuery.region"
        v-loading="loading"
        placeholder="区域"
        style="width:120px;"
        class="filter-item"
        clearable
        @change="handleSearch"
      >
        <el-option
          v-for="(item, index) in regions"
          :key="index"
          :label="item.regionName"
          :value="item.id"
        />
      </el-select>

      <!-- 搜索按钮 -->
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        :disabled="searchDisabled"
        @click="handleSearch"
      >
        搜索
      </el-button>

      <!-- 新增按钮 -->
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        新增
      </el-button>
    </div>

    <!-- 提示 -->
    <el-alert
      title="排班统一“上海时间”,不区分国家,时差等因素"
      type="success"
      :closable="false"
    />

    <!-- 表单 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row
    >
      <el-table-column prop="sysOrigin" label="来源系统" align="center">
        <template slot-scope="scope">
          <sys-origin-icon
            :icon="scope.row.sysOrigin"
            :desc="scope.row.sysOrigin"
          />
        </template>
      </el-table-column>
      <el-table-column label="客服" align="center">
        <template slot-scope="scope">
          <el-link
            v-if="scope.row.userProfile.id"
            @click="queryUserDetails(scope.row.userProfile.id)"
          >
            {{ scope.row.userProfile.userNickname }} /
            {{ scope.row.userProfile.account }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column prop="regionNameStr" label="区域" align="center" />
      <el-table-column label="上班时间段" align="center">
        <template slot-scope="scope">
          <span v-for="(item, index) in scope.row.timeSlots" :key="index">
            <el-tag style="margin: 2px 2px;">{{ item }}:00</el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="100"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            circle
            @click.native="handleEdit(scope.row)"
          />
          <el-button
            type="danger"
            icon="el-icon-delete"
            circle
            @click.native="del(scope.row)"
          />
        </template>
      </el-table-column>
    </el-table>

    <user-deatils-drawer
      v-if="userDeatilsDrawerVisible"
      :user-id="thatSelectedUserId"
      @close="userDeatilsDrawerVisible = false"
    />

    <el-dialog
      :title="textOptTitle"
      :visible.sync="formVisible"
      :before-close="handleClose"
      :close-on-click-modal="false"
      width="80%"
    >
      <div v-loading="submitLoading">
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-width="100px"
          style="margin-right: 50px;"
        >
          <el-form-item label="平台">
            <el-input
              v-model.trim="listQuery.sysOrigin"
              :disabled="true"
              type="text"
            />
          </el-form-item>
          <el-form-item v-if="form.id == ''" label="客服" prop="userId">
            <account-input
              v-model="form.userId"
              :sys-origin="listQuery.sysOrigin"
              placeholder="用户ID"
            />
          </el-form-item>
          <el-form-item label="区域" prop="regionList">
            <el-select
              v-model="form.regionList"
              v-loading="loading"
              multiple
              clearable
              placeholder="请选择"
              style="width:100%;"
              class="filter-item"
            >
              <el-option
                v-for="(item, index) in regions"
                :key="index"
                :label="item.regionName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="时间段" prop="timeSlots">
            <el-checkbox-group v-model="form.timeSlots">
              <el-checkbox-button
                v-for="slot in timeSlotList"
                :key="slot"
                :label="slot"
                >{{ slot }}:00</el-checkbox-button
              >
            </el-checkbox-group>
          </el-form-item>
          <el-form-item>
            <el-button v-if="form.id == ''" type="primary" @click="add()"
              >添加</el-button
            >
            <el-button v-if="form.id != ''" type="primary" @click="update()"
              >修改</el-button
            >
            <el-button @click="handleClose()">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCustomerService,
  addCustomerService,
  updateCustomerService,
  deleteCustomerService,
  regionConfigTable
} from "@/api/sys";
import { mapGetters } from "vuex";

function getFormData() {
  return {
    regionList: [],
    userId: "",
    sysOrigin: "",
    id: "",
    timeSlots: []
  };
}
export default {
  name: "CustomerService",
  props: {
    row: {
      type: Object,
      default: null
    },
    sysOrigin: {
      type: String,
      require: false,
      default: ""
    }
  },
  data() {
    const commonRules = [
      { required: true, message: "必填字段", trigger: "blur" }
    ];
    return {
      searchDisabled: false,
      userDeatilsDrawerVisible: false,
      thatSelectedUserId: "",
      formVisible: false,
      submitLoading: false,
      form: getFormData(),
      textOptTitle: "",
      list: [],
      timeSlotList: [
        0,
        1,
        2,
        3,
        4,
        5,
        6,
        7,
        8,
        9,
        10,
        11,
        12,
        13,
        14,
        15,
        16,
        17,
        18,
        19,
        20,
        21,
        22,
        23
      ],
      rangeDate: [],
      regions: [],
      listQuery: {
        region: "",
        sysOrigin: "ATYOU"
      },
      rules: {
        regionList: commonRules,
        userId: commonRules,
        sysOrigin: commonRules,
        timeSlots: commonRules
      },
      listLoading: true
    };
  },
  computed: {
    ...mapGetters(["permissionsSysOriginPlatforms"])
  },
  watch: {
    row: {
      handler(val) {
        if (!val) {
          this.listRegion();
          return;
        }
        const form = Object.assign({}, val);
        if (form.regions) {
          form.regionList = form.regions.split(",");
        }
        this.form = Object.assign(this.form, form);
        this.listRegion();
      },
      immediate: true
    }
  },
  created() {
    const that = this;
    const querySystem = this.permissionsSysOriginPlatforms[0];
    if (!querySystem) {
      return;
    }
    this.listRegion();
    that.listQuery.sysOrigin = querySystem.value;
    that.renderData();
  },
  methods: {
    renderData(isClean) {
      const that = this;
      if (isClean === true) {
        that.list = [];
      }
      that.listLoading = true;
      listCustomerService(that.listQuery.sysOrigin, that.listQuery.region).then(
        res => {
          const { body } = res;
          that.list = body;
          that.listLoading = false;
        }
      );
    },
    handleSearch() {
      this.renderData(true);
    },
    listRegion() {
      const that = this;
      that.loading = true;
      regionConfigTable({ sysOrigin: that.listQuery.sysOrigin })
        .then(res => {
          that.regions = res.body || [];
          that.loading = false;
        })
        .catch(er => {
          that.loading = false;
        });
    },
    handleCreate() {
      console.log(1111, this.form.userId);
      this.formVisible = true;
      this.form.userId = "";
    },
    handleEdit(row) {
      this.formVisible = true;
      this.form = row;
      this.form.userId = row.userProfile.account;
    },
    changeSysOrigin() {
      this.listRegion();
      this.handleSearch();
    },
    queryUserDetails(id) {
      this.userDeatilsDrawerVisible = true;
      this.thatSelectedUserId = id;
    },
    del(item) {
      const that = this;
      that
        .$confirm("确定删除客服人员吗", "提示", {
          type: "warning"
        })
        .then(() => {
          that.$message({
            message: "删除中，请等待结果",
            type: "warning"
          });
          that.listLoading = true;
          deleteCustomerService(item.id)
            .then(res => {
              that.listLoading = false;
              that.$message({
                message: "成功删除",
                type: "success"
              });
              that.renderData();
            })
            .catch(er => {
              console.error(er);
              that.listLoading = false;
            });
        })
        .catch(er => {
          console.error(er);
          that.listLoading = false;
        });
    },
    add() {
      const that = this;
      that.$refs.form.validate(valid => {
        if (!valid) {
          console.error("error submit!!");
          return false;
        }
        that.submitLoading = true;
        that.form.sysOrigin = that.listQuery.sysOrigin;
        addCustomerService(that.form)
          .then(res => {
            that.submitLoading = false;
            that.$emit("success", res);
            that.handleClose();
            that.renderData(true);
          })
          .catch(er => {
            that.submitLoading = false;
            that.$emit("fail");
            console.error(er);
          });
      });
    },
    update() {
      const that = this;
      that.Addormodify = false;
      that.$refs.form.validate(valid => {
        if (!valid) {
          console.error("error submit!!");
          return false;
        }
        that.submitLoading = true;
        updateCustomerService(that.form)
          .then(res => {
            that.submitLoading = false;
            that.$emit("success", res);
            that.handleClose();
            that.renderData(true);
          })
          .catch(er => {
            that.submitLoading = false;
            that.$emit("fail");
            console.error(er);
          });
      });
    },
    handleClose() {
      this.formVisible = false;
      this.resetForm();
    },
    resetForm() {
      this.form = getFormData();
    }
  }
};
</script>
<style scoped lang="scss">
.store-table-expand {
  font-size: 0;
  label {
    width: 90px;
    color: #99a9bf;
    .el-form-item {
      margin-right: 0;
      margin-bottom: 0;
      width: 50%;
    }
  }
}
</style>
