<template>
  <div class="app-container">
    <el-card>
      <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-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-card>
    <br>
    <el-card>
      <el-table border stripe height="600"  v-loading="loading" :data="supplierList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"  />
        <!--      <el-table-column label="ID"  prop="id" width="50"  />-->
        <el-table-column label="供应商编号"  prop="supplierNo" width="100" />
        <el-table-column label="供应商名称"  prop="supplierName" width="200" />
        <el-table-column label="供应商类型"  prop="principalType" width="100" />
        <el-table-column label="主体识别号/身份证号"  prop="principalId" width="200" />
        <el-table-column label="车辆号码" prop="carNum" width="150"></el-table-column>
        <el-table-column label="联系电话"  prop="phone"  width="120"/>
        <el-table-column label="供应类型"  prop="supplySpecies">
          <template slot-scope="scope">
            <span>{{animalName(scope.row.supplySpecies)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="经营地点"  prop="businessPlace" width="300" />
        <!-- <el-table-column label="产地"  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="所在省市县"  prop="region">
          <template slot-scope="scope">{{scope.row.region?getCodeToText(scope.row.region,null):"-"}}</template>
        </el-table-column> -->
        <el-table-column label="评分"  prop="evaluate">
          <template slot-scope="scope">
            <template v-if="scope.row.evaluate">
<!--              <el-tooltip class="item" effect="dark" content="点击编辑当前评分" placement="top-start">-->
<!--                <div class="btn_blue" @click="editEvaluate(scope.row)">{{scope.row.evaluate}}</div>-->
<!--              </el-tooltip>-->
              <el-popover
                placement="top-start"
                title="评分"
                trigger="hover"
                content="点击编辑当前评分">
                <el-button slot="reference" size="mini" type="primary" @click="editEvaluate(scope.row)">{{scope.row.evaluate}}</el-button>
              </el-popover>
            </template>
            <template v-else>
              <span>暂无评分</span>
            </template>
          </template>
        </el-table-column>
        <!-- <el-table-column label="备注"  prop="remark" /> -->
        <el-table-column label="黑名单"  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="250"  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>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-plus"
              @click="addEvaluate(scope.row)">新增评价</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-card>

    <!-- 添加或修改供应商对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" label-position="left" :rules="rules" :disabled="isView" label-width="130px">
            <el-form-item label="供应商编号" prop="supplierNo">
              <el-input v-model="form.supplierNo" disabled show-word-limit maxlength="3" :placeholder="isView ? '' : '请输入供应商编号'" />
            </el-form-item>
            <el-form-item label="供应商名称" prop="supplierName">
              <el-input v-model="form.supplierName" type="textarea" :autosize="{ minRows: 2 }"   show-word-limit maxlength="30"  :placeholder="isView ? '' : '请输入供应商名称'" />
            </el-form-item>
            <el-form-item label="供应商类型" prop="principalType">
              <el-radio-group v-model="form.principalType">
                <el-radio label="企业">企业</el-radio>
                <el-radio label="个体户">个体户</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item :label="form.principalType === '企业' ? '主体识别号' : '身份证号'" prop="principalId">
              <el-input v-model="form.principalId" :placeholder="isView ? '' : form.principalType === '企业' ? '请输入主体识别号' : '请输入身份证号'"></el-input>
            </el-form-item>
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" :placeholder="isView ? '' :'请输入联系电话'" />
            </el-form-item>
            <el-form-item
              v-for="(item, i) in form.carNumList"
              :key="i"
              :label="'车辆号码-' + (i + 1) + (i === 0 ? '(默认)': '')"
              :prop="`carNumList.${i}.value`"
              :rules="carRules">
              <el-input
                v-model="item.value"
                placeholder="请输入车辆号码"
                class="result-input"
                style="width: 200px"
              />
              <el-button
                style="margin-left: 10px"
                class="result-add"
                type="primary"
                v-if="i == form.carNumList.length - 1"
                @click="addCar"
              ><i class="el-icon-plus"></i
              ></el-button>
              <el-button
                class="result-del"
                type="danger"
                style="margin-left: 10px"
                v-if="i > 0 || form.carNumList.length > 1"
                @click="removeCar(i)"
              ><i class="el-icon-minus"></i
              ></el-button>
            </el-form-item>
            <el-form-item label="供应类型" prop="supplySpecies">
              <el-select v-model="form.supplySpecies">
                <el-option v-for="(item, i) in animalList" :key="i" :value="item.typeValue" :label="item.typeName"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="经营地点" prop="businessPlace">
              <el-input v-model="form.businessPlace" type="textarea" :autosize="{ minRows: 2 }"   show-word-limit maxlength="50"  :placeholder="isView ? '' :'请输入经营地点'" />
            </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>
    <evaluate ref="evaluates" @refresh="refresh"></evaluate>
  </div>
</template>

<script>
import { listSupplier,getSupplier, delSupplier, addSupplier, updateSupplier, getSupplierNo } from "@/api/app/supplier";
import { regionData, regionDataPlus, CodeToText, TextToCode } from 'element-plus-china-area';
import {patchZero} from "@/utils/str.js";
import {required, rules} from "../../../utils/formRules";

import Evaluate from "./components/evaluate.vue";
import {mapState} from "vuex";
export default {
  name: "Supplier",
  components: { Evaluate },
  dicts: ['app_origin_type','app_supply_type','app_in_blacklist',"app_supplier_evaluate"],
  // components:{
  //   VueAreaLinkage
  // },
  data() {
    // 自定义车牌校验规则
    const validatePlate = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('车牌号不能为空'));
      }

      // 车牌号正则（简化版，可根据需求调整）
      const plateReg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/;

      if (!plateReg.test(value)) {
        return callback(new Error('请输入正确的车牌号'));
      }

      // 校验车牌是否重复
      const plates = this.form.carNumList.map(item => item.value);
      const duplicateCount = plates.filter(plate => plate === value).length;

      if (duplicateCount > 1) {
        return callback(new Error('车牌号不能重复'));
      }

      callback();
    };

    // 验证主体识别码
    const validateNumber = (rule, value, callback) => {
      if (!/^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/.test(value)) {
        return callback(new Error('请输入18位有效的主体识别码'));
      }
      callback();
    };
    const validateIdCard = (rule, value, callback) => {
      if (!/(^\d{8}(0\d|10|11|12)([0-2]\d|30|31)\d{3}$)|(^\d{6}(18|19|20)\d{2}(0[1-9]|10|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$)/.test(value)) {
        return callback(new Error('请输入有效的身份证号'));
      }
      callback();
    };
    var validatePhone = (rule, value, callback) => {
      if (value === undefined || value === null || value.trim() === '') {
         callback();
      } else {
        let phoneRegex = /^(?:(?:(?:13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[0-9])\d{8})|(?:0\d{2,3}-\d{7,8})(?:-\d{1,6})?)$/
        if(!phoneRegex.test(value)) {
          callback(new Error('请填写正确格式的联系方式'));
        } else {
          callback()
        }
      }

    };
    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:[],
      // 车牌校验规则
      carRules: [
        {
          required: true,
          message: '车辆号码不能为空',
          trigger: 'blur',
        },
        { validator: validatePlate, trigger: 'blur' }
      ],
      // 表单校验
      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: [{ validator: validatePhone,  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" }],
        principalId: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                // 如果没填，直接通过
                return callback();
              }
              // 如果填了，根据 type 校验
              if (this.form.principalType === '企业') {
                validateNumber(rule, value, callback);
              } else if (this.form.principalType === '个体户') {
                validateIdCard(rule, value, callback);
              } else {
                callback();
              }
            }
          }
        ],
      },
      showModal: false,
    };
  },
  computed: {
    ...mapState({
      animalList: state => state.user.animalList
    }),
    animalName() {
      return (value) => {
        if (value === null) return '未知'
        const animal = this.animalList.find(item =>
          String(item.typeValue) === String(value)
        )
        return animal ? animal.typeName : '未知'
      }
    }
  },
  created() {
    this.getList();
  },
  methods: {
    addCar() {
      this.form.carNumList.push({
        value: "",
      });
    },
    removeCar(i) {
      this.form.carNumList.splice(i, 1);
    },
    /** 查询供应商列表 */
    getList() {
      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,
        carNumList: [{value: null}],
        carNum: null,
        principalType: '企业',
        principalId: null,
        supplySpecies: 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();
      getSupplierNo().then(res => {
        this.form.supplierNo = res.data.nextNo
      })
      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
        let arr = this.form.carNum ? this.form.carNum.split(',').map(item => ({value: item})) : [{value: ''}]
        this.$set(this.form, 'carNumList', arr)
        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
        let arr = this.form.carNum ? this.form.carNum.split(',').map(item => ({value: item})) : [{value: ''}]
        this.$set(this.form, 'carNumList', arr)
        this.open = true;
        this.isView = true;
        this.title = "查看供应商";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.region = this.form.regionArr?this.form.regionArr.join(","):"";
      console.log(this.form.carNumList)
      this.form.carNum = this.form.carNumList.map(item => item.value).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;
      this.$modal.confirm('是否确认删除所选数据项？').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`)
    },
    // 新增评价
    addEvaluate(item) {
      let user = {
        supplierId: item.id,
        supplierName: item.supplierName,
        edit: false
      }
      this.$refs.evaluates.openModal(user)
    },
    editEvaluate(item) {
      console.log(111)
      let user = {
        supplierId: item.id,
        supplierName: item.supplierName,
        edit: true
      }
      this.$refs.evaluates.openModal(user)
    },
    refresh() {
      this.getList()
    },
  }
};
</script>
<style scoped>
.btn_blue {
  color: #20a0ff;
  cursor: pointer;
}
</style>
