<template>
  <div class="app-container" style="padding: 20px 50px">
    <el-form
        :inline="true"
        label-position="right"
        label-width="170px"
        :model="formLabelAlign"
        style="max-width: 90%"
        ref="ruleFormRef"
        :rules="rules"
        class="ruleFormRef"
    >
        <el-form-item label="派遣公司名称" prop="name">
          <el-input v-model="formLabelAlign.name" maxlength="100" />
        </el-form-item>
        <el-form-item label="默认账号" prop="default_account">
          <el-input v-model="formLabelAlign.default_account" maxlength="20" placeholder="请输入账号(手机号格式)" :disabled="formLabelAlign.id"/>
        </el-form-item>
        <el-form-item label="编号" prop="base_code">
          <el-input v-model="formLabelAlign.base_code" :disabled="formLabelAlign.id" />
        </el-form-item>
        <el-form-item label="前缀" prop="prefix">
          <el-input v-model="formLabelAlign.prefix" onkeyup="value=value.replace(/[^a-zA-Z]/g,'')"/>
        </el-form-item>
        <el-form-item label="规模" prop="scale">
            <el-select
                v-model="formLabelAlign.scale"
                placeholder="请选择"
                filterable
                style="width: 190px;"
            >
              <el-option label="请选择" value="" />
              <el-option label="微型" value="微型" />
              <el-option label="小型" value="小型" />
              <el-option label="中型" value="中型" />
              <el-option label="大型" value="大型" />
              <el-option label="特大型" value="特大型" />
            </el-select>
        </el-form-item>
        <el-form-item label="注册日期" prop="register_time">
          <el-date-picker
              v-model="formLabelAlign.register_time"
              type="date"
              placeholder="注册日期"
              value-format="YYYY-MM-DD"
              style="width: 200px"
          />
        </el-form-item>
      <el-form-item label="联系人" prop="contracts">
        <el-input v-model="formLabelAlign.contracts" maxlength="20" />
      </el-form-item>
      <el-form-item label="联系电话" prop="contract_number">
        <el-input v-model="formLabelAlign.contract_number" />
      </el-form-item>
      <el-form-item label="公司地址（省市县区）" prop="ssq_id">
        <el-cascader v-model="formLabelAlign.ssq_id" :options="regionData" @change="handleSsqChange()" style="width: 200px"/>
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input v-model="formLabelAlign.address"  maxlength="50"/>
      </el-form-item>
  </el-form>

    <el-form-item style="width: 100%;">
      <div style="margin: 0 auto;">
        <el-button @click="cancel">取消</el-button>
        <el-button @click="submitForm" type="primary" >提交</el-button>
      </div>
    </el-form-item>

</div>

</template>

<script setup>

import { reactive, ref, getCurrentInstance } from 'vue'
import {
  provinceAndCityData,
  pcTextArr,
  regionData,
  pcaTextArr,
  codeToText,
} from "element-china-area-data";

import {checkAccount, checkBaseCode, checkName, dispatchC, dispatchU, getDetails} from "@/api/dispatch";

const { proxy } = getCurrentInstance();
const id = proxy.$route.query.id || '' // 编辑时数据id

// 页面
const formLabelAlign = ref({
})

const rules = ref({
  name: [{ required: true, message: "请输入派遣公司名称", trigger: ['blur', 'change']},
         { validator: validateName, trigger: 'blur' }
  ],
  default_account:[
    { required: true, message: "请输入默认账号", trigger: ['blur', 'change']},
    { pattern: /^(((19[0-9]{1})|(16[0-9]{1})|(17[0-9]{1})|(13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/, message: "请输入正确的账号(手机号)", trigger: "blur" },
    { validator: validateAccount, trigger: 'blur' }
  ],
  base_code:[
    { required: true, message: "请输入编号", trigger: ['blur', 'change']},
    { pattern: /^[a-z\-0-9]{6,10}$/gi, message: "请输入6到10位的字符", trigger: "blur" },
    { validator: validateBaseCode, trigger: 'blur' }
  ],
  prefix: [{ required: true, message: "请输入前缀", trigger: ['blur', 'change']}],
  register_time:[{ validator: validateTime, trigger: ['blur', 'change'] }],
  contract_number: [{ pattern: /^\d[0-9\-]{5,11}\d$/, message: "请输入正确的手机号或座机号", trigger: "blur" }],
  contracts: [{ required: true, message: "请输入联系人", trigger: ['blur', 'change']}],
})

//编辑时获取详情
if(id){
  getDetails({id: id}).then(({ data }) => {
    formLabelAlign.value = {
      id:id,
      name: data.name,
      default_account: data.defaultAccount,
      base_code: data.baseCode,
      prefix: data.prefix,
      scale: data.scale,
      register_time: data.registerTime,
      contracts: data.contracts,
      contract_number: data.contractNumber,
      ssq_id: [data.provinceId,data.cityId,data.countyId],
      address: data.address,
    }
  })
}

//校验名称是否重复
function validateName(rule, value, callback) {
  if(formLabelAlign.value.id!=='' && formLabelAlign.value.id!==undefined){
    callback();
  }
  checkName({name:value,id:formLabelAlign.value.id}).then((response) => {
    if (!response.data) {
      callback(new Error('名称重复'));
    } else {
      callback();
    }
  });
}
//校验默认账号是否重复
function validateAccount(rule, value, callback) {
  if(formLabelAlign.value.id!=='' && formLabelAlign.value.id!==undefined){
    callback();
  }
  checkAccount({default_account:value}).then((response) => {
    if (!response.data) {
      callback(new Error('默认账号重复'));
    } else {
      callback();
    }
  });
}
//校验baseCode是否重复
function validateBaseCode(rule, value, callback) {
  if(formLabelAlign.value.id!=='' && formLabelAlign.value.id!==undefined){
    callback();
  }
  checkBaseCode({base_code:value,id:formLabelAlign.value.id}).then((response) => {
    if (!response.data) {
      callback(new Error('编号重复'));
    } else {
      callback();
    }
  });
}
//校验注册日期
function validateTime(rule, value, callback) {
  if (!value) {
    callback();
  }
  let now = new Date();
  let date = new Date(value);
  if (date > now) {
    callback(new Error("注册日期不能超过当前日期"));
  }else {
    callback();
  }
}

function handleSsqChange () {
  let ssq_id = formLabelAlign.value.ssq_id;
  formLabelAlign.value.province_id = ssq_id[0];
  formLabelAlign.value.city_id = ssq_id[1];
  formLabelAlign.value.county_id = ssq_id[2];
  formLabelAlign.value.district = codeToText[formLabelAlign.value.province_id] + '-' + codeToText[formLabelAlign.value.city_id] + '-' + codeToText[formLabelAlign.value.county_id];
}

/** 取消 */
function cancel(){
  proxy.$router.go(-1);
}

/** 提交 */
function submitForm(){
  proxy.$refs.ruleFormRef.validate(async (valid) => {
    if (!valid) return;
    const submitForm = {...formLabelAlign.value}
    if(formLabelAlign.value.id){
      dispatchU(submitForm).then(res => {
        proxy.$modal.msgSuccess(res.code)
        const obj = { path: "/dispatch" };
        proxy.$tab.closeOpenPage(obj);
      })
    }else {
      dispatchC(submitForm).then(res => {
        proxy.$modal.msgSuccess(res.code)
        const obj = { path: "/dispatch" };
        proxy.$tab.closeOpenPage(obj);
      })
    }
  })
}


</script>