<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户编号" prop="customerCode">
        <el-input v-model="queryParams.customerCode" placeholder="请输入客户编号" clearable style="width: 250px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable style="width: 250px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="成立日期" prop="registDate">
        <el-date-picker v-model="queryParams.registDate" style="width: 250px" value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']" />
      </el-form-item>
      <el-form-item label="联系人" prop="customerPerson">
        <el-input v-model="queryParams.customerPerson" placeholder="请输入客户名称" clearable style="width: 250px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="手机号" prop="customerPersonPhone">
        <el-input v-model="queryParams.customerPersonPhone" placeholder="请输入客户名称" clearable style="width: 250px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="是否开启" prop="isOpen">
        <el-select v-model="queryParams.isOpen" placeholder="状态" clearable style="width: 250px">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.COMMON_STATUS)" :key="parseInt(dict.value)"
            :label="dict.label" :value="parseInt(dict.value)" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['customer:info:create']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
          v-hasPermi="['customer:info:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList">
      <el-table-column label="序号" type="index" width="50"align="center"/>
      <el-table-column label="客户编号" align="center" prop="customerCode" min-width="350" />
      <el-table-column label="客户名称" align="center" prop="customerName" min-width="150" />
      <el-table-column label="客户成立日期" align="center" prop="registDate" min-width="100" />
      <el-table-column label="注册资本金(万元)" align="center" prop="capital" min-width="150" />
      <el-table-column label="法人代表" align="center" prop="legalPerson" min-width="100" />
      <el-table-column label="员工人数" align="center" prop="workforce" min-width="100" />
      <el-table-column label="联系人" align="center" prop="customerPerson" min-width="100" />
      <el-table-column label="联系人手机号" align="center" prop="customerPersonPhone" min-width="150" />
      <el-table-column label="是否开启" align="center">
        <template v-slot="scope">
          <el-switch v-model="scope.row.isOpen" :active-value="0" :inactive-value="1" @change="handleStatusChange(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="creatorEmployeeName" min-width="100" />
      <el-table-column label="创建时间" align="center" prop="createTime" min-width="150">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" min-width="150">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['customer:info:update']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['customer:info:delete']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-detail" @click="handleDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="客户编号" prop="customerCode">
              <el-input v-model="form.customerCode" placeholder='请输入客户名称'></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="客户名称" prop="customerName">
              <el-input maxlength="30" v-model="form.customerName" placeholder='请输入客户名称'></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="成立日期" prop="registDate">
              <el-date-picker value-format="yyyy-MM-dd" v-model="form.registDate" type="date" placeholder="选择日期"
                style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
              <el-form-item label="注册资金" prop="capital">
                  <el-input v-model="form.capital" placeholder='请输入注册资本金(万元)'></el-input>
              </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="法人代表" prop="legalPerson">
              <el-input maxlength="10" v-model="form.legalPerson" placeholder='请输入法人代表'></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="员工人数" prop="workforce">
              <el-input-number v-model="form.workforce" :min="1" label="员工人数" style="width: 100%;"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="客户地址" prop="companyAddress">
              <el-input maxlength="30" v-model="form.companyAddress" placeholder='请输入客户地址'></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="联系人" prop="customerPerson">
              <el-input maxlength="10" v-model="form.customerPerson" placeholder='请输入客户联系人'></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="手机号" prop="customerPersonPhone">
              <el-input v-model="form.customerPersonPhone" placeholder='请输入客户联系手机号'></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="办公地址" prop="companyPersonAddress">
              <el-input maxlength="30" v-model="form.companyPersonAddress" placeholder='请输入客户联系人办公地址'></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="附件">
              <el-upload :action="fileUrl" :headers="headers" :file-list="files" :on-success="handleFileSuccessCite"
                :before-upload="beforeUploadFile" :on-remove="handleRemove" :on-preview="handlePreview">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input maxlength="200" rows="4" show-word-limit type="textarea" v-model="form.remarks"
                placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 详情对话框 -->
    <el-dialog :title="title" :visible.sync="openDetail" width="800px" append-to-body>
      <div class="widget-wrapper">
    <div class="widget-list">
      <div class="fx-field x-grid-col-12">
        <div class="field-label">
          <span class="field-required">*</span>
          <div class="field-name">客户编号</div>
        </div>
        <div class="field-component">
          <span :title="form.customerCode">{{ form.customerCode }}</span>
        </div>
      </div>
      <div class="fx-field x-grid-col-12">
        <div class="field-label">
          <span class="field-required">*</span>
          <div class="field-name">客户名称</div>
        </div>
        <div class="field-component">
          <span :title="form.customerName">{{ form.customerName }}</span>
        </div>
      </div>
      <div class="fx-field x-grid-col-12">
        <div class="field-label">
          <span class="field-required">*</span>
          <div class="field-name">成立日期</div>
        </div>
        <div class="field-component">
          <span :title="form.registDate">{{ form.registDate }}</span>
        </div>
      </div>
      <div class="fx-field x-grid-col-12">
        <div class="field-label">
          <span class="field-required">*</span>
          <div class="field-name">注册资金</div>
        </div>
        <div class="field-component">
          <span :title="form.capital">{{ form.capital }}</span>
        </div>
      </div>


      <div class="fx-field x-grid-col-12">
        <div class="field-label">
          <span class="field-required">*</span>
          <div class="field-name">法人代表</div>
        </div>
        <div class="field-component">
          <span :title="form.legalPerson">{{ form.legalPerson }}</span>
        </div>
      </div>
      <div class="fx-field x-grid-col-12">
        <div class="field-label">
          <div class="field-name">员工人数</div>
        </div>
        <div class="field-component">
          <span :title="form.workforce">{{ form.workforce }}</span>
        </div>
      </div>

      <div class="fx-field x-grid-col-12">
        <div class="field-label">
          <span class="field-required">*</span>
          <div class="field-name">客户地址</div>
        </div>
        <div class="field-component">
          <span :title="form.companyAddress">{{ form.companyAddress }}</span>
        </div>
      </div>
      <div class="fx-field x-grid-col-12">
        <div class="field-label">
          <span class="field-required">*</span>
          <div class="field-name">联系人</div>
        </div>
        <div class="field-component">
          <span :title="form.customerPerson">{{ form.customerPerson }}</span>
        </div>
      </div>
      <div class="fx-field x-grid-col-12">
        <div class="field-label">
          <span class="field-required">*</span>
          <div class="field-name">手机号</div>
        </div>
        <div class="field-component">
          <span :title="form.customerPersonPhone">{{ form.customerPersonPhone }}</span>
        </div>
      </div>
      <div class="fx-field x-grid-col-12">
        <div class="field-label">
          <div class="field-name">办公地址</div>
        </div>
        <div class="field-component">
          <span :title="form.companyPersonAddress">{{ form.companyPersonAddress }}</span>
        </div>
      </div>

      <div class="fx-field x-grid-col-12">
        <div class="field-label">
          <div class="field-name">附件</div>
        </div>
        <div class="field-component">
          <div v-for="(item, index) in form.fileList" :key="index">
            <a :href="item.url" target="_blank" :title="item.name" style="color: #5094d5;">{{ item.name }}</a>
          </div>
        </div>
       
      </div>
      <div class="fx-field x-grid-col-12">
        <div class="field-label">
          <div class="field-name">备注</div>
        </div>
        <div class="field-component">
          <span :title="form.remarks">{{ form.remarks }}</span>
        </div>
      </div>
    </div>
  </div>
    </el-dialog>
  </div>
</template>

<script>
import { changeUserStatus,getCustomerCode,listCustomer, getCustomer, delCustomer, addCustomer, updateCustomer, exportCustomer } from "@/api/crm/customer";
import { getBaseHeader } from "@/utils/request";
import {CommonStatusEnum} from "@/utils/constants";
export default {
  data() {
    return {
      files: [],
      // 设置上传的请求头部
      headers: getBaseHeader(),
      // 上传的地址
      fileUrl: process.env.VUE_APP_BASE_API + '/admin-api/infra/file/uploaData',
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openDetail: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        customerCode: undefined,
        customerName: undefined,
        registDate: [],
        customerPerson: undefined,
        customerPersonPhone: undefined,
        isOpen:undefined,
        
      },
      // 枚举
      SysCommonStatusEnum: CommonStatusEnum,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        customerCode: [
          { required: true, message: '请输入客户编号', trigger: 'blur' },
        ],
        customerName: [
          { required: true, message: '请输入客户名称', trigger: 'blur' },
        ],
        registDate: [
          { required: true, message: '请选择成立日期', trigger: 'blur' }
        ],
        capital: [
          { required: true, message: '请输入金额', trigger: 'blur' },
          {
              pattern: /^(([1-9]{1}\d{0,9})|(0{1}))(\.\d{1,2})?$/,
              message: "请输入合法的金额数字，最多两位小数",
              trigger: "blur"
          }
        ],
        legalPerson: [
          { required: true, message: '请输入法人代表', trigger: 'blur' },
        ],
        companyAddress: [
          { required: true, message: '请输入客户地址', trigger: 'blur' },
        ],
        customerPerson: [
          { required: true, message: '请输入联系人', trigger: 'blur' },
        ],
        customerPersonPhone: [
          {
            required: true,
            pattern: /^(?:(?:\+|00)86)?1(?:3[\d]|4[5-79]|5[0-35-9]|6[5-7]|7[0-8]|8[\d]|9[189])\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getCustomerCode(){
      getCustomerCode().then(response => {
        this.form.customerCode = response.data;
      });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      let fileIds = [];
      for (let i in fileList) {
        let id = fileList[i].response.data.id;
        fileIds.push(id);
      }
      this.form.fileIdList = fileIds;
    },
    handlePreview(file) {
      console.log("file", file);
      var link = document.createElement("a"); //定义一个a标签
      link.download = file.name; //下载后的文件名称
      link.href = file.url; //需要生成一个 URL 来实现下载
      link.click(); //模拟在按钮上实现一次鼠标点击
      window.URL.revokeObjectURL(link.href);
    },
    beforeUploadFile(file) {
      console.log(file);
      const size = file.size / 1024 / 1024;
      console.log(size);
      if (size > 5) {
        this.$message.error("文件大小不能超过5MB！");
        return false;
      }
    },
    handleFileSuccessCite(res, file, fileList) {
      console.log(file, fileList);
      console.log("------", "==========");
      console.log("res = ", res);

      let fileIds = [];
      for (let i in fileList) {
        let response = fileList[i].response;
        if (response.errno && response.errno != "0") {
          this.$message.error("该文件上传失败,已被移除,请重新上传!");
          // 上传失败移除该 file 对象
          fileList.splice(i, 1);
        } else {
          let id = fileList[i].response.data.id;
          fileIds.push(id);
        }
      }
      this.form.fileIdList = fileIds;
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      listCustomer(this.queryParams).then(response => {
        this.dataList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
      // 用户状态修改
      handleStatusChange(row) {
      let text = row.isOpen === CommonStatusEnum.ENABLE ? "开启" : "关闭";
      this.$modal.confirm('确认要"' + text + '""' + row.customerName + '"客户吗?').then(function() {
          return changeUserStatus(row.id, row.isOpen);
        }).then(() => {
          this.$modal.msgSuccess(text + "成功");
          this.getList();
        }).catch(function() {
          row.isOpen = row.isOpen === CommonStatusEnum.ENABLE ? CommonStatusEnum.DISABLE
              : CommonStatusEnum.ENABLE;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.files = [],
      this.form = {
        customerCode: undefined,
        customerName: undefined,
        registDate: undefined,
        capital: undefined,
        legalPerson: undefined,
        workforce: 1,
        companyAddress: undefined,


        customerPerson: undefined,
        customerPersonPhone: undefined,
        companyPersonAddress: undefined,
        fileIdList: undefined,
        remarks: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getCustomerCode();
      this.open = true;
      this.title = "添加";
    },

    /** 详情按钮操作 */
    handleDetail(row) {
      this.reset();
      const id = row.id;
      getCustomer(id).then(response => {
        this.form = response.data;
        this.openDetail = true;
        this.title = "详情";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getCustomer(id).then(response => {
        let files = response.data.fileList;
        if (files) {
          this.files = [];
          for (let i in files) {
            let url = files[i].url;
            let name = files[i].name;
            let id = files[i].id;

            this.files.push({
              name: name,
              url: url,
              response: { error: "0", data: { url: url, id: id } },
            });
          }
        }
        this.form = response.data;
        this.open = true;
        this.title = "修改";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            updateCustomer(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCustomer(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除数据项?').then(function () {
        return delCustomer(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = { ...this.queryParams };
      params.pageNo = undefined;
      params.pageSize = undefined;
      // 执行导出
      this.$modal.confirm('是否确认导出所有数据项?').then(() => {
        this.exportLoading = true;
        return exportCustomer(params);
      }).then(response => {
        this.$download.excel(response, '客户信息.xls');
        this.exportLoading = false;
      }).catch(() => { });
    }
  }
};
</script>
<style lang="scss" scoped>
.widget-wrapper>.widget-list {
  display: flex;
  flex-wrap: wrap;
}

.x-grid-col-6 {
  width: 50%;
}

.x-grid-col-12 {
  width: 100%;
}

.fx-field {
  line-height: 20px;
  padding: 7px 12px 12px;
  position: relative;
}

.fx-field .field-label {
  word-wrap: break-word;
  color: #141e31;
  display: flex;
  font-weight: 600;
  line-height: 20px;
  padding: 5px 0;
  position: relative;
  word-break: break-word;
}

.fx-field .field-label .field-required {
  color: #eb5050;
  margin-left: -6px;
  position: relative;
}

.fx-field .field-label .field-name {
  overflow: hidden;
}

.field-component {
  word-wrap: break-word;
  background: #f5f6f8;
  border-radius: 2px;
  color: #141e31;
  font-size: 14px;
  line-height: 20px;
  min-height: 32px;
  padding: 6px 8px;
  white-space: pre-wrap;
  word-break: break-word;
}

ul {
  padding-left: 0px !important;
}

.el-tag+.el-tag {
  margin-left: 10px;
}
</style>