<template>
  <div style="background-color: #fff">
    <div class="inner-toolbar">
      <div class="toolbar-btns">
        <el-button
          size="mini"
          v-if="checkPermission(['finance-income:add'])"
          type="primary"
          @click="handleAddSupplier"
          >新增</el-button
        >
        <el-button size="mini" type="primary"  v-if="checkPermission(['finance-income:delete'])">删除</el-button>
      </div>
      <div class="toolbar-menu">
        <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
          <el-tab-pane label="销售和租赁" name="CUSTOMER_ALL"></el-tab-pane>
          <el-tab-pane label="销售客户" name="CUSTOMER_SALE"></el-tab-pane>
          <el-tab-pane label="租赁客户" name="CUSTOMER_LEASE"></el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <en-table-layout :tableData="tableData.data" :loading="loading">
      <div class="toolbar"></div>
      <template slot="table-columns">
        <el-table-column prop="id" label="客户id" />
        <el-table-column prop="name" label="公司名称" />
        <el-table-column prop="contact" label="联系人姓名" />
        <el-table-column prop="gender" label="性别" />
        <el-table-column prop="mobile" label="手机号" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="type" label="客户类别">
          <template slot-scope="scope">
            {{ deliveryType(scope.row.type) }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="status" label="状态" /> -->
        <el-table-column label="操作" width="350px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              v-if="checkPermission(['customer:update'])"
              @click="handleEditSupplier(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              v-if="checkPermission(['finance-income:delete'])"
              type="danger"
              @click="handleDeleteSupplier(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </template>

      <el-pagination
        v-if="tableData"
        slot="pagination"
        @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange"
        :current-page="tableData.page_no"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="tableData.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.data_total"
      >
      </el-pagination>
    </en-table-layout>
    <el-dialog
      :title="supplierForm.id ? '编辑客户信息' : '添加客户信息'"
      :visible.sync="dialogVisible"
      width="1100px"
      @open="handleDialogOpen"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="supplierForm"
        :rules="supplierRules"
        ref="supplierForm"
        label-width="120px"
        inline
      >
        <!-- <el-form-item label="公司名称" prop="custom_name">
          <el-input v-model="supplierForm.custom_name" :minlength="2" :maxlength="20" clearable
            placeholder="请输入公司名称"></el-input>
        </el-form-item> -->
        <el-form-item label="公司名称" prop="name">
          <el-input
            v-model="supplierForm.name"
            :minlength="2"
            :maxlength="20"
            clearable
            placeholder="请输入联系人"
          ></el-input>
        </el-form-item>
        <el-form-item label="客户联系人" prop="contact ">
          <el-input
            v-model="supplierForm.contact"
            :minlength="2"
            :maxlength="20"
            clearable
            placeholder="请输入客户联系人"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio v-model="supplierForm.gender" label="男">男</el-radio>
          <el-radio v-model="supplierForm.gender" label="女">女</el-radio>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input
            v-model="supplierForm.mobile"
            :minlength="2"
            :maxlength="20"
            clearable
            placeholder="请输入手机号码"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮件" prop="email">
          <el-input
            v-model="supplierForm.email"
            :minlength="2"
            clearable
            placeholder="请输入电子邮件"
          ></el-input>
        </el-form-item>
        <el-form-item label="客户类别" prop="type">
          <!-- <el-input v-model="supplierForm.type" :minlength="2" :maxlength="20" clearable
            placeholder="请输入客户类别"></el-input> -->
          <el-select v-model="supplierForm.type" placeholder="请选择客户类别">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="状态" prop="status">
          <el-input v-model="supplierForm.status" :minlength="2" :maxlength="20" clearable
            placeholder="请输入客户状态"></el-input>
        </el-form-item> -->
        <!-- <el-form-item label="状态" prop="real_name">
          <el-input v-model="supplierForm.real_name" :minlength="2" :maxlength="20" clearable
            placeholder="请输入客户状态"></el-input>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitSupplierForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as API_BasicSetting from "@/api/basicSetting";
import { RegExp } from "~/ui-utils";
import * as API_Setting from "@/api/setting";
import { Foundation } from "~/ui-utils";
export default {
  name: "supplier",
  data() {
    return {
      deptList: [],
      // 列表loading状态
      loading: false,
      // 列表参数
      params: {
        page_no: 1,
        page_size: 10,
        type: "CUSTOMER_ALL",
      },
      // 列表数据
      tableData: "",
      // 高级搜索数据
      advancedForm: {
        dept_id: "",
      },
      // 供应商表单
      supplierForm: {},
      // 供应商表单 规则
      supplierRules: {
        custom_sn: [
          this.MixinRequired("请输入客户编号！"),
          { min: 2, max: 20, message: "长度在 2 到 20 个字符" },
          {
            validator: (rule, value, callback) => {
              if (value && !RegExp.userName.test(value)) {
                callback(new Error("只支持汉字、字母、数字、“-”、“_”的组合！"));
              } else {
                callback();
              }
            },
          },
        ],
        postal_address: [this.MixinRequired("请输入通讯地址！")],
        telephone: [
          this.MixinRequired("请输入联系电话！"),
          {
            validator: (rule, value, callback) => {
              if (!RegExp.mobile.test(value)) {
                callback(new Error("联系电话格式有误！"));
              } else {
                callback();
              }
            },
            trigger: ["change", "blur"],
          },
        ],
        name: [this.MixinRequired("请输入联系人！")],
        mobile: [
          this.MixinRequired("请输入手机号码！"),
          {
            validator: (rule, value, callback) => {
              if (!RegExp.mobile.test(value)) {
                callback(new Error("手机号码格式有误！"));
              } else {
                callback();
              }
            },
            trigger: ["change", "blur"],
          },
        ],
        gender: [{ required: true, message: "请选择性别", trigger: "change" }],
        type: [
          { required: true, message: "请选择客户类别", trigger: "change" },
        ],
        contact: [
          { required: true, message: "请输入客户联系人", trigger: "blur" },
        ],
      },
      // 供应商表单 dialog
      dialogVisible: false,
      activeName: "CUSTOMER_ALL",
      options: [
        /* {
          value: '全部',
          label: '全部'
        },{
          value: '销售客户',
          label: '销售客户'
        }, {
          value: '租赁客户',
          label: '租赁客户'
        }, */
      ],
    };
  },
  mounted() {
    this.GET_SupplierList();
    this.GET_DeptList();
  },
  methods: {
    deliveryType(val) {
      let name = "";
      this.options.map((el) => {
        if (el.value == val) {
          return (name = el.label);
        }
      });
      return name;
    },
    handleClick(tab) {
      this.activeName = tab.name;
      this.params.type = tab.name;
      this.GET_SupplierList();
    },
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then((response) => {
        this.deptList = Foundation.buildTree(response, "0");
      });
      API_Setting.getPage({ dictType: "customer_type" }).then((res) => {
        this.options = res.data;
      });
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size;
      this.GET_SupplierList();
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page;
      this.GET_SupplierList();
    },

    /** 添加供应商 */
    handleAddSupplier() {
      this.supplierForm = {
        founder: 0,
        real_name: "",
        password: "",
      };
      this.dialogVisible = true;
    },

    /** 编辑供应商 */
    handleEditSupplier(index, row) {
      this.supplierForm = this.MixinClone(row);
      parseInt(this.supplierForm.role_id) === 0
        ? (this.supplierForm.role_id = "超级供应商")
        : null;
      this.dialogVisible = true;
    },

    /** 删除供应商 */
    handleDeleteSupplier(index, row) {
      this.$confirm("确定要删除这个供应商吗？", "提示", { type: "warning" })
        .then(() => {
          API_BasicSetting.deleteCustomer(row.id).then(() => {
            this.$message.success("删除成功！");
            this.GET_SupplierList();
          });
        })
        .catch(() => {});
    },
    /** dialog打开后重置form表单校验结果 */
    handleDialogOpen() {
      setTimeout(() => {
        this.$refs["supplierForm"].clearValidate();
      });
    },

    /** 提交供应商表单 */
    submitSupplierForm() {
      this.$refs["supplierForm"].validate((valid) => {
        if (valid) {
          const { id } = this.supplierForm;
          const params = this.MixinClone(this.supplierForm);
          if (id) {
            API_BasicSetting.editCustomer(id, params).then((response) => {
              this.dialogVisible = false;
              this.$message.success("修改成功！");
              this.GET_SupplierList();
            });
          } else {
            API_BasicSetting.addCustomer(params).then(() => {
              this.dialogVisible = false;
              this.$message.success("添加成功！");
              this.GET_SupplierList();
            });
          }
        } else {
          this.$message.error("表单填写有误，请核对！");
          return false;
        }
      });
    },

    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        keyword: data,
      };
      this.params.page_no = 1;
      this.GET_SupplierList();
    },

    /** 获取供应商列表 */
    GET_SupplierList() {
      this.loading = true;
      API_BasicSetting.customer(this.params)
        .then((response) => {
          this.loading = false;
          this.tableData = response;
        })
        .catch(() => {
          this.loading = false;
        });
    },
  },
};
</script>

<style type="text/scss" lang="scss" scoped>
.inner-toolbar {
  padding: 20px 20px 0;
  .toolbar-menu {
    margin-top: 20px;
  }
}
.form-item-remark {
  width: 1000px;
}

.form-item-remark-input {
  width: 845px;
}

.face-image {
  display: block;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

/deep/ .el-dialog__body {
  padding: 10px 20px;
}
</style>
