<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="肉商编号" prop="purchaserNo">
        <el-input
          v-model="queryParams.purchaserNo"
          placeholder="请输入肉商编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="肉商名称" prop="purchaserName">
        <el-input
          v-model="queryParams.purchaserName"
          placeholder="请输入肉商名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="销售去向" prop="phone">
        <el-select v-model="queryParams.salePlace">
            <el-option
              v-for="dict in dict.type.app_origin_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
      </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="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['app:purchaser:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['app:purchaser:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="purchaserList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="ID" align="center" prop="id" width="50" /> -->
      <el-table-column label="肉商编号" align="center" prop="purchaserNo" />
      <el-table-column label="肉商名称" align="center" prop="purchaserName" />
      <el-table-column label="身份证号" align="center" prop="idNumber" />
      <el-table-column label="联系电话" align="center" prop="phone" />
      <el-table-column label="经营地点" align="center" prop="businessPlace" />
      <el-table-column label="销售去向" align="center" prop="salePlace">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.app_origin_type" :value="scope.row.salePlace"/>
        </template>
      </el-table-column>
      <el-table-column label="所在省市县" align="center" prop="region">
        <template slot-scope="scope">{{scope.row.region?getCodeToText(scope.row.region,null):"-"}}</template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['app:purchaser:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['app:purchaser:remove']"
          >删除</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="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" :disabled="isView" label-width="120px">
        <el-form-item label="肉商编号" prop="purchaserNo">
          <el-input v-model="form.purchaserNo" placeholder="请输入肉商编号" />
        </el-form-item>
        <el-form-item label="肉商名称" prop="purchaserName">
          <el-input v-model="form.purchaserName" placeholder="请输入肉商名称" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idNumber">
          <el-input v-model="form.idNumber" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="经营地点" prop="businessPlace">
          <el-input v-model="form.businessPlace" placeholder="请输入经营地点" />
        </el-form-item>
        <el-form-item label="销售去向" prop="salePlace">
          <el-select v-model="form.salePlace">
            <el-option
              v-for="dict in dict.type.app_origin_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所在省市县" prop="region">
          <el-cascader
            size="large"
            :options="regionOptions"
            v-model="form.regionArr"
            @change="handleChange">
          </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!isView">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPurchaser, getPurchaser, delPurchaser, addPurchaser, updatePurchaser } from "@/api/app/purchaser";
import { regionData, regionDataPlus, CodeToText, TextToCode } from 'element-plus-china-area';
import {patchZero} from "@/utils/str.js"
export default {
  name: "Purchaser",
  dicts: ['app_origin_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      nos: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 肉商表格数据
      purchaserList: [],
      // 弹出层标题
      title: "",
      isView:false,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        purchaserNo:null,
        purchaserName: null,
        salePlace: null,
      },
      regionOptions:regionData,
      regionArr:[],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        purchaserNo: [
          { required: true, message: "肉商编号不能为空", trigger: "blur" },
          {
              pattern: /^\d{1,3}$/,
              message: '肉商编号输入超出最大长度限制（3位数字）',
              trigger: 'blur'
          },
          { min: 1, max: 3, message: "肉商编号输入超出最大长度限制（3位数字）", trigger: "blur" },
        ],
        purchaserName: [
          { required: true, message: "肉商名称不能为空", trigger: "blur" },
          { min: 1, max: 30, message: "肉商名称输入超出最大长度限制（30位）", trigger: "blur" },
        ],
        region: [{ required: true, message: "所在省市县不能为空", trigger: "blur" }],
        // phone: [
        //   { required: true, message: "联系电话不能为空", trigger: "blur" },
        //   {
        //       pattern: /^1[3-9]\d{9}$/,
        //       message: '联系电话格式输入错误',
        //       trigger: 'blur'
        //   },
        // ],
        idNumber: [
          {
              pattern: /^$|^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$/,
              message: '身份证号格式输入错误',
              trigger: 'blur'
          },
        ],
        businessPlace: [{ min: 0, max: 50, message: "经营地点输入超出最大长度限制（50位）", trigger: "blur" },],
        salePlace: [{ required: true, message: "销售去向不能为空", trigger: "blur" }],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询肉商列表 */
    getList() {
      this.loading = true;
      listPurchaser(this.queryParams).then(response => {
        this.purchaserList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        purchaserNo:null,
        purchaserName: null,
        idNumber: null,
        phone: null,
        businessPlace: null,
        salePlace: this.dict.type.app_origin_type[0] ? this.dict.type.app_origin_type[0].value: null,
        region: null,
        regionArr:[],
      };
      this.resetForm("form");
    },
    handleChange (value) {
	      console.log(value)
	      //this.getCodeToText(null, value)

	    },
	   getCodeToText (codeStr, codeArray) {
	      if (null === codeStr && null === codeArray) {
	        return null;
	      } else if (null === codeArray) {
	        codeArray = codeStr.split(",");
	      }
	      let area = "";
	      switch (codeArray.length) {
	        case 1:
	          area += CodeToText[codeArray[0]];
	          break;
	        case 2:
	          area += CodeToText[codeArray[0]] + "/" + CodeToText[codeArray[1]];
	          break;
	        case 3:
	          area +=
            CodeToText[codeArray[0]] +
	            "/" +
	            CodeToText[codeArray[1]] +
	            "/" +
	            CodeToText[codeArray[2]];
	          break;
	        default:
	          break;
	      }
	      console.log(area)
	      return area;
	    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.salePlace = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.nos = selection.map(item => item.purchaserNo)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isView = false;
      this.title = "添加肉商";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPurchaser(id).then(response => {
        this.form = response.data;
        this.form.regionArr = this.form.region?this.form.region.split(","):null
        this.open = true;
        this.isView = false;
        this.title = "修改肉商";
      });
    },
    /** 修改按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id || this.ids
      getPurchaser(id).then(response => {
        this.form = response.data;
        this.form.regionArr = this.form.region?this.form.region.split(","):null
        this.open = true;
        this.isView = true;
        this.title = "查看肉商";
      });
    },
    /** 提交按钮 */
    submitForm() {

      this.form.region = this.form.regionArr?this.form.regionArr.join(","):"";
      console.log(this.form.region)
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.purchaserNo){
            this.form.purchaserNo = patchZero(this.form.purchaserNo,3);
          }
          if (this.form.id != null) {
            updatePurchaser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPurchaser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const nos = row.purchaserNo || this.nos;
      this.$modal.confirm('是否确认删除肉商编号为"' + nos + '"的数据项？').then(function() {
        return delPurchaser(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('app/purchaser/export', {
        ...this.queryParams
      }, `purchaser_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
