<template>
  <div>
    <en-table-layout :tableData="tableData.data" :loading="loading">
      <div slot="toolbar" class="inner-toolbar">
        <div class="toolbar-btns">
          <el-button size="mini" v-if="checkPermission(['supplier:add'])" type="primary"
            @click="handleAddSupplier">新增</el-button>
        </div>
        <div class="toolbar-search">
          <en-table-search @search="searchEvent" placeholder="请输入关键字搜索">
          </en-table-search>
        </div>
      </div>
      <template slot="table-columns">
        <el-table-column prop="custom_name" label="供应商名称" />
        <el-table-column prop="custom_sn" label="供应商编码" />
        <el-table-column prop="production_address" label="供应商地址" />
        <el-table-column prop="transfer" label="传真" />
        <el-table-column prop="linkman" label="联系人" />
        <el-table-column prop="telephone" label="电话" />
        <el-table-column prop="email" label="电子邮件" />
        <el-table-column label="操作" width="350px">
          <template slot-scope="scope">
            <el-button size="mini" v-if="checkPermission(['supplier:edit'])"
              @click="handleEditSupplier(scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini" v-if="checkPermission(['supplier:del'])" 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="transfer">
          <el-input v-model="supplierForm.transfer" :minlength="2" :maxlength="20" clearable
            placeholder="请输入传真"></el-input>
        </el-form-item>
        <el-form-item label="邮政编码" prop="zipcode">
          <el-input v-model="supplierForm.zipcode" :minlength="2" :maxlength="20" clearable
            placeholder="请输入邮政编码"></el-input>
        </el-form-item>
        <el-form-item label="通讯地址" prop="postal_address">
          <el-input v-model="supplierForm.postal_address" :minlength="2" :maxlength="20" clearable
            placeholder="请输入通讯地址"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="telephone">
          <el-input v-model="supplierForm.telephone" :minlength="2" :maxlength="20" clearable
            placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="公司网站" prop="company_website">
          <el-input v-model="supplierForm.company_website" :minlength="2" :maxlength="20" clearable
            placeholder="请输入公司网站"></el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="linkman">
          <el-input v-model="supplierForm.linkman" :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" :maxlength="20" clearable
            placeholder="请输入电子邮件"></el-input>
        </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="production_address">
          <el-input v-model="supplierForm.production_address" :minlength="2" :maxlength="20" clearable
            placeholder="请输入生产地址"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark" class="form-item-remark">
          <el-input v-model="supplierForm.remark" type="textarea" :autosize="{ minRows: 3, maxRows: 4 }"
            placeholder="请输入备注" class="form-item-remark-input"></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
      },
      // 列表数据
      tableData: '',
      // 高级搜索数据
      advancedForm: {
        dept_id: ''
      },
      // 供应商表单
      supplierForm: {},
      // 供应商表单 规则
      supplierRules: {
        custom_name: [
          this.MixinRequired('请输入客户名称！'),
          { min: 2, max: 20, message: '长度在 2 到 20 个字符' },
          {
            validator: (rule, value, callback) => {
              if (value && !RegExp.userName.test(value)) {
                callback(new Error('只支持汉字、字母、数字、“-”、“_”的组合！'))
              } else {
                callback()
              }
            }
          }
        ],
        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']
          }
        ],
        linkman: [this.MixinRequired('请输入联系人！')],
        mobile: [
          this.MixinRequired('请输入手机号码！'),
          {
            validator: (rule, value, callback) => {
              if (!RegExp.mobile.test(value)) {
                callback(new Error('手机号码格式有误！'))
              } else {
                callback()
              }
            },
            trigger: ['change', 'blur']
          }
        ]
      },
      // 供应商表单 dialog
      dialogVisible: false
    }
  },
  mounted() {
    this.GET_SupplierList()
    this.GET_DeptList()
  },
  methods: {
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then(response => {
        this.deptList = Foundation.buildTree(response, '0')
      })
    },
    /** 分页大小发生改变 */
    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.deleteSupplier(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.editSupplier(id, params).then(response => {
              this.dialogVisible = false
              this.$message.success('修改成功！')
              this.GET_SupplierList()
            })
          } else {
            API_BasicSetting.addSupplier(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.getSupplierList(this.params).then(response => {
        this.loading = false
        this.tableData = response
      }).catch(() => { this.loading = false })
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
.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>
