<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="supplierNo">
        <el-input
          v-model="queryParams.supplierNo"
          placeholder="请输入供应商编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商名称" prop="supplierName">
        <el-input
          v-model="queryParams.supplierName"
          placeholder="请输入供应商名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应类型" prop="phone">
        <el-select v-model="queryParams.supplySpecies">
            <el-option
              v-for="dict in dict.type.app_supply_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:supplier: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:supplier:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="supplierList" @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="supplierNo" width="100" />
      <el-table-column label="供应商名称" align="center" prop="supplierName" />
      <el-table-column label="联系电话" align="center" prop="phone" />
      <el-table-column label="供应类型" align="center" prop="supplySpecies">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.app_supply_type" :value="scope.row.supplySpecies"/>
        </template>
      </el-table-column>
      <el-table-column label="经营地点" align="center" prop="businessPlace" />
      <!-- <el-table-column label="产地" align="center" prop="originPlace">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.app_origin_type" :value="scope.row.originPlace"/>
        </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="评价" align="center" prop="evaluate">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.app_supplier_evaluate" :value="scope.row.evaluate"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column label="黑名单" align="center" prop="inBlacklist">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.app_in_blacklist" :value="scope.row.inBlacklist"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="180" 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:supplier:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['app:supplier: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="supplierNo">
          <el-input v-model="form.supplierNo" placeholder="请输入供应商编号" />
        </el-form-item>
        <el-form-item label="供应商名称" prop="supplierName">
          <el-input v-model="form.supplierName" 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="supplySpecies">
          <el-select v-model="form.supplySpecies">
            <el-option
              v-for="dict in dict.type.app_supply_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="经营地点" prop="businessPlace">
          <el-input v-model="form.businessPlace" placeholder="请输入经营地点" />
        </el-form-item>
        <!-- <el-form-item label="产地" prop="originPlace">
          <el-select v-model="form.originPlace">
            <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

            :options="regionOptions"
            v-model="form.regionArr"
            @change="handleChange">
          </el-cascader>

        </el-form-item> -->
        <el-form-item label="评价" prop="evaluate">
          <el-select v-model="form.evaluate">
            <el-option
              v-for="dict in dict.type.app_supplier_evaluate"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="黑名单" prop="inBlacklist">
          <el-select v-model="form.inBlacklist">
            <el-option
              v-for="dict in dict.type.app_in_blacklist"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </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 { listSupplier,getSupplier, delSupplier, addSupplier, updateSupplier } from "@/api/app/supplier";
import { regionData, regionDataPlus, CodeToText, TextToCode } from 'element-plus-china-area';
import {patchZero} from "@/utils/str.js";
export default {
  name: "Supplier",
  dicts: ['app_origin_type','app_supply_type','app_in_blacklist',"app_supplier_evaluate"],
  // components:{
  //   VueAreaLinkage
  // },
  data() {
    return {

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      nos: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 供应商表格数据
      supplierList: [],
      // 弹出层标题
      title: "",
      //是否查看
      isView:false,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        supplierNo: null,
        supplierName: null,
        supplySpecies: null,
      },
      // 表单参数
      form: {},
      //地区
      regionOptions:regionData,
      regionArr:[],
      // 表单校验
      rules: {
        supplierNo: [
          { required: true, message: "供应商编号不能为空", trigger: "blur" },
          {
              pattern: /^\d{1,3}$/,
              message: '供应商编号输入超出最大长度限制（3位数字）',
              trigger: 'blur'
          },
          { min: 1, max: 3, message: "供应商编号输入超出最大长度限制（3位数字）", trigger: "blur" },
        ],
        supplierName: [
          { required: true, message: "供应商名称不能为空", trigger: "blur" },
          { min: 1, max: 30, message: "供应商名称输入超出最大长度限制（30位）", trigger: "blur" },
        ],
        supplySpecies: [{ required: true, message: "供应类型不能为空", trigger: "change" }],
        phone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" },
          {
              pattern: /^1[3-9]\d{9}$/,
              message: '联系电话格式输入错误',
              trigger: 'blur'
          },
        ],
        businessPlace: [{ min: 0, max: 50, message: "经营地点输入超出最大长度限制（50位）", trigger: "blur" },],
        originPlace: [{ required: true, message: "产地不能为空", trigger: "change" }],
        evaluate: [{ required: true, message: "评价不能为空", trigger: "change" }],
        inBlacklist: [{ required: true, message: "黑名单状态不能为空", trigger: "change" }],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询供应商列表 */
    getList() {
      this.loading = true;
      listSupplier(this.queryParams).then(response => {
        this.supplierList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        supplierNo:null,
        supplierName: null,
        phone: null,
        supplySpecies: this.dict.type.app_supply_type[0] ? this.dict.type.app_supply_type[0].value: null,
        businessPlace: null,
        originPlace: this.dict.type.app_origin_type[0] ? this.dict.type.app_origin_type[0].value: null,
        region: null,
        regionArr:[],
        evaluate: this.dict.type.app_supplier_evaluate[0] ? this.dict.type.app_supplier_evaluate[0].value: null,
        inBlacklist: this.dict.type.app_in_blacklist[0] ? this.dict.type.app_in_blacklist[0].value: null,
      };

      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.queryParams.supplySpecies = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.nos = selection.map(item => item.supplierNo)
      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
      getSupplier(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
      getSupplier(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(","):"";
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.supplierNo){
            this.form.supplierNo = patchZero(this.form.supplierNo,3);
          }

          if (this.form.id != null) {
            updateSupplier(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSupplier(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const nos = row.supplierNo || this.nos;
      console.log(this.nos)
      this.$modal.confirm('是否确认删除供应商编号为"' + nos + '"的数据项？').then(function() {
        return delSupplier(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('app/supplier/export', {
        ...this.queryParams
      }, `supplier_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
