<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="公司名" prop="companyId">
        <el-select filterable style="width: 220px" v-model="queryParams.corpId" placeholder="请选择公司名" clearable size="small">
          <el-option
            v-for="item in companys"
            :key="item.companyId"
            :label="item.companyName"
            :value="item.companyId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="转移类型" prop="transferType">
        <el-select v-model="queryParams.transferType" placeholder="请选择转移类型" clearable size="small" style="width: 220px">
          <el-option
            v-for="item in transferTypeList"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"/>
        </el-select>
      </el-form-item>
      <el-form-item label="目标销售" prop="targetUserId">
        <el-select v-model="queryParams.targetUserId" remote
                   placeholder="请选择" filterable clearable
                   style="width: 220px;" @keyup.enter.native="handleQuery" :remote-method="getAllUserListLimitQuery">
          <el-option
            v-for="dict in companyUserList"
            :key="`${dict.nickName} - ${dict.userName}`"
            :label="`${dict.nickName} - ${dict.userName}`"
            :value="dict.userId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发起人" prop="initiatorUserId">
        <el-select v-model="queryParams.initiatorUserId" remote placeholder="请选择" filterable clearable
                   style="width: 220px;" @keyup.enter.native="handleQuery"
                   :remote-method="getAllUserListLimitQuery3"
        >
          <el-option
            v-for="dict in companyUserList3"
            :key="`${dict.nickName} - ${dict.userName}`"
            :label="`${dict.nickName} - ${dict.userName}`"
            :value="dict.userId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审批状态" prop="approvalStatus">
        <el-select v-model="queryParams.approvalStatus" placeholder="请选择审批状态" clearable size="small" style="width: 220px">
          <el-option
            v-for="item in approvalStatusList"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"/>
        </el-select>
      </el-form-item>
      <el-form-item label="审批时间" prop="processedAt">
        <el-date-picker clearable size="small" style="width: 220px"
                        v-model="queryParams.processedAt"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择审批处理时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="创建时间" prop="createdAt">
        <el-date-picker clearable size="small" style="width: 220px"
                        v-model="queryParams.createdAt"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择记录创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间" prop="updatedAt">
        <el-date-picker clearable size="small" style="width: 220px"
                        v-model="queryParams.updatedAt"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择记录更新时间">
        </el-date-picker>
      </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="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:approval:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="approvalList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="所属公司" align="center" prop="companyName" />
      <el-table-column label="转移类型" align="center" prop="transferTypeText" />
      <el-table-column label="目标销售" align="center" prop="targetUserName" />
      <el-table-column label="发起转移用户" align="center" prop="initiatorUserName" />
      <el-table-column label="转移内容/原因" align="center" prop="content" />
      <el-table-column label="审批状态" align="center" prop="approvalStatus" >
        <template slot-scope="scope">
          <el-tag :type="scope.row.approvalStatus == 1 ? 'success' : scope.row.approvalStatus == 2 ? 'danger' : ''">{{ scope.row.approvalStatusText }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审批意见/备注" align="center" prop="approvalRemark" />
      <el-table-column label="记录创建时间" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="记录最后更新时间" align="center" prop="updatedAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.approvalStatus == 0"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="viewMode=false;handleUpdate(scope.row)"
            v-hasPermi="['system:approval:edit']"
          >审批</el-button>
          <el-button
            v-if="scope.row.approvalStatus != 0"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="viewMode=true;handleUpdate(scope.row)"
            v-hasPermi="['system:approval:edit']"
          >查看</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="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="企业" prop="corpId">
          <el-input v-model="form.companyName" placeholder="企业" disabled="disabled"/>
        </el-form-item>
        <el-form-item label="转移类型" prop="transferType">
          <el-input v-model="form.transferTypeText" placeholder="转移类型" disabled="disabled"/>
        </el-form-item>
        <el-form-item label="转移矩阵" prop="customerIds">
          <el-table :data="form.customerList" border>
            <el-table-column label="客户" align="center" prop="userName" />
            <el-table-column label="转移前销售" align="center" prop="beforeCompanyUserName" />
            <el-table-column label="转移后销售" align="center" prop="afterCompanyUserName" />
          </el-table>
        </el-form-item>
        <el-form-item label="目标接收销售用户" prop="targetUserId">
          <el-input v-model="form.targetUserName" placeholder="请输入目标接收销售用户 ID" disabled="disabled"/>
        </el-form-item>
        <el-form-item label="发起此转移请求的用户" prop="initiatorUserId">
          <el-input v-model="form.initiatorUserName" placeholder="请输入发起此转移请求的用户 ID" disabled="disabled"/>
        </el-form-item>
        <el-form-item label="转移提示内容/原因">
          <el-input v-model="form.content" :min-height="192" disabled="disabled"/>
        </el-form-item>
        <el-form-item label="审批状态">
          <el-radio-group v-model="form.approvalStatus">
            <el-tag>{{form.approvalStatusText}}</el-tag>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批意见/备注" prop="approvalRemark">
          <el-input v-model="form.approvalRemark" type="textarea" placeholder="请输入内容"  disabled="disabled"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click="submitForm(1)" v-if="!viewMode">通过</el-button>
        <el-button type="danger" @click="submitForm(2)" v-if="!viewMode">拒绝</el-button>
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listApproval, getApproval, delApproval, addApproval, updateApproval, exportApproval } from "@/api/user/approval";
import Editor from '@/components/Editor';
import {getDicts} from "@/api/system/dict/data";
import {getCompanyList} from "@/api/company/company";
import {getAllUserListLimit} from "@/api/store/user";

export default {
  name: "Approval",
  components: { Editor },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户转移审批表格数据
      approvalList: [],
      companys:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 转移类型
      transferTypeList: [],
      companyUserList: [],
      companyUserList3: [],
      // 审批状态
      approvalStatusList: [],
      viewMode: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        corpId: null,
        transferType: null,
        customerIds: null,
        originalUserId: null,
        targetUserId: null,
        initiatorUserId: null,
        content: null,
        approvalStatus: null,
        approverUserId: null,
        approvalRemark: null,
        processedAt: null,
        createdAt: null,
        updatedAt: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        corpId: [
          { required: true, message: "企业不能为空", trigger: "blur" }
        ],
        transferType: [
          { required: true, message: "转移类型不能为空", trigger: "change" }
        ],
        customerIds: [
          { required: true, message: "客户 ID 列表不能为空", trigger: "blur" }
        ],
        targetUserId: [
          { required: true, message: "目标接收销售用户不能为空", trigger: "blur" }
        ],
        initiatorUserId: [
          { required: true, message: "发起此转移请求的用户不能为空", trigger: "blur" }
        ],
        approvalStatus: [
          { required: true, message: "审批状态不能为空", trigger: "blur" }
        ],
        createdAt: [
          { required: true, message: "记录创建时间不能为空", trigger: "blur" }
        ],
        updatedAt: [
          { required: true, message: "记录最后更新时间不能为空", trigger: "blur" }
        ],
        approvalRemark: [
          { required: true, message: "审批意见不能为空!", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    getDicts('transfer_type').then(response => {
      this.transferTypeList = response.data;
    })
    getDicts('transfer_approval_status').then(response => {
      this.approvalStatusList = response.data;
    })
    getAllUserListLimit().then(res=>{
      if(res.code === 200) {
        this.companyUserList = res.data
      }
    });
    getAllUserListLimit().then(res=>{
      if(res.code === 200) {
        this.companyUserList3 = res.data
      }
    });
    getCompanyList().then(response => {
      this.companys = response.data;
    });
    this.getList();
  },
  methods: {
    getAllUserListLimitQuery(keywords){
      getAllUserListLimit({
        keywords: keywords
      }).then(res=>{
        if(res.code === 200) {
          this.companyUserList = res.data
        }
      });
    },
    getAllUserListLimitQuery3(keywords){
      getAllUserListLimit({
        keywords: keywords
      }).then(res=>{
        if(res.code === 200) {
          this.companyUserList3 = res.data
        }
      });
    },
    /** 查询客户转移审批列表 */
    getList() {
      this.loading = true;
      listApproval(this.queryParams).then(response => {
        this.approvalList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        corpId: null,
        transferType: null,
        customerIds: null,
        originalUserId: null,
        targetUserId: null,
        initiatorUserId: null,
        content: null,
        approvalStatus: 0,
        approverUserId: null,
        approvalRemark: null,
        processedAt: null,
        createdAt: null,
        updatedAt: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加客户转移审批";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getApproval(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改客户转移审批";
      });
    },
    /** 提交按钮 */
    submitForm(type) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateApproval({...this.form,approvalStatus: type}).then(response => {
              if (response.code === 200) {
                this.msgSuccess(response.msg);
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除客户转移审批编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delApproval(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有客户转移审批数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportApproval(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>
