<template xmlns="">
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="150px">   
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item :label="$t('编号')" prop="name">
            <el-input
              v-model="form.name"
              :placeholder="$t('请输入编号')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('跟进状态')">
            <el-select
              v-model="form.status"
              :placeholder="$t('请选择')"
            >
              <el-option
                v-for="dict in getDictDatas(DICT_TYPE.CUSTOMER_FOLLOWUP_STATUS)"
                :key="dict.value"
                :label="isChinese ? dict.label : dict.labelEn"
                :value="parseInt(dict.value)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('客户编号')" prop="source">
            <el-input
              v-model="form.name"
              :placeholder="$t('请输入客户名称')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('跟进类型')" prop="followType">
            <el-select
              v-model="form.followType"
              :placeholder="$t('请选择')"
            >
              <el-option
                v-for="dict in getDictDatas(DICT_TYPE.CUSTOMER_FOLLOWUP_TYPE)"
                :key="dict.value"
                :label="isChinese ? dict.label : dict.labelEn"
                :value="parseInt(dict.value)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="13">
          <el-form-item :label="$t('报价单')">
            <el-input
              v-model="form.offerId"
              :placeholder="$t('请输入报价单')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('跟进时间')">
            <el-date-picker
              v-model="form.followTime"
              type="datetime"
              :placeholder="$t('请选择')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('联系人')" prop="source">
            <el-input
              v-model="form.name"
              :placeholder="$t('请输入客户名称')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('客户经理')" prop="followUserId">
            <el-select
              v-model="form.followUserId"
              :placeholder="$t('请选择客户经理')"
            >
              <el-option
                v-for="item in serviceUserList"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('跟进方式')" prop="followMethod">
            <el-select
              v-model="form.followMethod"
              :placeholder="$t('请选择')"
            >
              <el-option
                v-for="dict in getDictDatas(DICT_TYPE.CUSTOMER_FOLLOWUP_METHOD)"
                :key="dict.value"
                :label="isChinese ? dict.label : dict.labelEn"
                :value="parseInt(dict.value)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('上一级跟进单')" prop="parentNumber">
            <el-input
              v-model="form.parentNumber"
              :placeholder="$t('请输入上一级跟进单')"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="$t('目的')" prop="purpose">
            <el-input
              type="textarea"
              :rows="2"
              v-model="form.purpose"
              :placeholder="$t('请输入目的')"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="$t('跟进结果')" prop="followMethod">
            <el-select
              v-model="form.resultType"
              :placeholder="$t('请选择')"
            >
              <el-option
                v-for="dict in getDictDatas(DICT_TYPE.CUSTOMER_FOLLOWUP_RESULT_TYPE)"
                :key="dict.value"
                :label="isChinese ? dict.label : dict.labelEn"
                :value="parseInt(dict.value)"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="$t('情况')" prop="address">
            <el-input
              v-model="form.address"
              :placeholder="$t('请输入联系地址')"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="$t('附件')" prop="attatchment">
            <FileUpload :limit="1" :isShowTip=false v-model="form.attatchment" :fileType="fileType" />
          </el-form-item>
        </el-col>
    
        <el-col :span="12">
          <el-form-item :label="$t('下次跟进时间')">
            <el-date-picker
              v-model="form.nextTime"
              type="datetime"
              value-format="timestamp"
              disabled
              :placeholder="$t('选择创建时间')"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('下一步计划')" prop="nextPlan">
            <el-input
              type="textarea"
              :rows="2"
              v-model="form.nextPlan"
              :placeholder="$t('请输入下一步计划')"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="$t('创建人')" prop="founder">
            <el-select v-model="form.founder" disabled>
              <el-option
                v-for="item in allSimplList"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('创建时间')" prop="createTime">
            <el-date-picker
              v-model="form.createTime"
              type="datetime"
              value-format="timestamp"
              disabled
              :placeholder="$t('选择创建时间')"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('最后更新人')">
            <el-select v-model="form.updater" disabled>
              <el-option
                v-for="item in allSimplList"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('最后更新时间')">
            <el-date-picker
              v-model="form.updateTime"
              type="datetime"
              value-format="timestamp"
              disabled
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div style="margin-top: 15px; text-align: center">
      <el-button type="warning" @click="goBack">{{
        $t("返 回")
      }}</el-button>
      <el-button type="primary" @click="submitForm">{{
        $t("保 存")
      }}</el-button>
      <el-button type="success" @click="submitResult">{{ $t("提交结果") }}</el-button>
    </div>
  </div>
</template>

<script>
import { getDictDatas, DICT_TYPE } from "@/utils/dict";
import upload from "@/components/ImageUpload";
import FileUpload from "@/components/FileUpload";
import {
  createCustomer,
  getCustomer,
  getCustomerList,
  getCustomerPage,
  memberUserList,
  updateCustomer,
  userMemberUserList,
  getCustomerLines,
  fillupCustomeInfo,
  getServiceNetwork,
  addCompetitor,
  competitorListAll
} from "@/api/ecw/customer";
import { getNodeList } from "@/api/ecw/node";
import { getProductTypeList } from "@/api/ecw/productType";
import { getProductList } from "@/api/ecw/product";
import { getTradeCityList } from "@/api/ecw/region";
import { getWarehouseList } from "@/api/ecw/warehouse";
import CustomerLineTable from "@/components/CustomerLineTable";
import { getCustomerSelect } from "@/api/ecw/customer";
import {
  listAllSimpl,
  listServiceUser,
  listSimpleUsers,
} from "@/api/system/user";
import { getZhongPaoBest, getZhongPaoPage } from "@/api/ecw/zhongPao";
import { getCustomerContactsListByCustomer } from "@/api/ecw/customerContacts";
import { getCountryListAll } from "@/api/ecw/country";
import Template from "@/views/cms/template";
import { validatorMobile } from "@/api/ecw/validate";
// import {customerDropDownList} from "@/api/ecw/customerCommissionInfo";
import MemberSelector from "@/components/MemberSelector";
import { getCurrencyList } from "@/api/ecw/currency";
export default {
  name: "EcwCustomerEdit",

  components: {
    Template,
    upload,
    CustomerLineTable,
    MemberSelector,
    FileUpload
  },
  created() {
    this.reset();
    listServiceUser().then((r) => {
      this.serviceUserList = r.data;
    })
  },
  data() {
    return {
      fileTypes: ["doc","xls","ppt","txt","pdf","png","jpg","jpeg"],
      getDictDatas,
      DICT_TYPE,

      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {
            required: true,
            message: this.$t("客户名称不能为空"),
            trigger: "blur",
          },
        ],
        country: [
          { required: true, message: this.$t("国家不能为空"), trigger: "blur" },
        ],
        level: [
          {
            required: true,
            message: this.$t("客户等级不能为空"),
            trigger: "blur",
          },
        ],
        type: [
          {
            required: true,
            message: this.$t("客户类别不能为空"),
            trigger: "blur",
          },
        ],
        createTime: [
          {
            required: true,
            message: this.$t("创建时间不能为空"),
            trigger: "blur",
          },
        ],
        source: [
          {
            required: true,
            message: this.$t("客户来源不能为空"),
            trigger: "blur",
          },
        ],
        customerService: [
          {
            required: this.customerId === "0",
            message: this.$t("客户经理不能为空"),
            trigger: "blur",
          },
        ],
        status: [
          {
            required: true,
            message: this.$t("客户状态不能为空"),
            trigger: "blur",
          },
        ],
        busiCountryIds: [
          {
            required: true,
            message: this.$t("请选择业务国家"),
            trigger: "change",
          },
        ],
        competitorIds: [
          {
            required: true,
            message: this.$t("请选择主要竞争对手"),
            trigger: "change",
          },
        ],
      },
      contactRules: {
        name: [
          { required: true, message: this.$t("请输入联系人"), trigger: "blur" },
        ],
        areaCode: [
          { required: true, message: this.$t("请选择区号"), trigger: "change" },
          {
            required: true,
            trigger: "change",
            validator: this.codeValidator,
          },
        ],
        phoneNew: [
          {
            required: true,
            trigger: "blur",
            validator: this.phoneValidator,
          },
        ],
      },
      // 网点
      nodeList: [],
      productTypeList: [],
      productList: [],
      showZhong: false,
      showZhong1: false,
      showPao: false,
      showPao1: false,
      warehouseList: [], // 仓库列表
      importCityList: [], // 进口地址
      customerSelect: [],
      recommended: [],
      serviceUserList: [],
      countryList: [],

      zhongLines: [], // 重货线路
      paoLines: [], // 泡货线路
      memberList: [], //会员列表
      selectMemberList: [], //选中会员列表
      serviceNetworkList: [], //网点列表
      allSimplList: [],
      currecyList: [],
      enterOpenSeaTime: undefined,
      showBaseFlag: true,
      showShippingFlag: true,
      showSettingFlag: true,
      showFinanceFlag: true,
      competitorList: [],
    };
  },

  methods: {
    addEmail(row) {
      row.push("");
    },
    deleteEmail(row, index) {
      row.splice(index, 1);
    },
    change(val) {
      this.form.productIds = [];
      this.getProductListFn(val);
    },
    getProductListFn(val) {
      getProductList({ typeId: val }).then((r) => {
        this.productList = r.data;
      });
    },
    deleteBankData(index) {
      this.form.customerBanks.splice(index, 1);
    },
    remoteMethod(val) {
      this.getCustomerSelect(val);
    },
    getCustomerSelect(val = "") {
      getCustomerSelect({ pageNo: 1, pageSize: 30, searchKey: val }).then(
        (res) => {
          this.customerSelect = res.data.list;
        }
      );
    },
    phoneValidator(rule, value, callback) {
      if (!value) {
        return callback(new Error(this.$t("请输入联系方式")));
      }
      let areaCode = this.form.customerContacts.find(
        (e) => e.phoneNew === value
      ).areaCode;
      if (areaCode) {
        validatorMobile({
          code: areaCode,
          mobile: value,
        })
          .then((r) => {
            if (r.data) {
              callback();
            } else {
              callback(new Error(r.msg || this.$t("手机号验证失败")));
            }
          })
          .catch((e) => {
            console.error(e);
            callback(new Error(this.$t("手机号验证失败")));
          });
      }
    },
    codeValidator(rule, value, callback) {
      let index = +rule.field.split(".")[1];
      let phone = this.form.customerContacts[index].phoneNew;
      if (phone) {
        validatorMobile({
          code: value,
          mobile: phone,
        })
          .then((r) => {
            if (r.data) {
              callback();
            } else {
              callback();
              this.$message.error(r.msg || this.$t("手机号验证失败"));
            }
          })
          .catch((e) => {
            console.error(e);
            callback();
            this.$message.error(this.$t("手机号验证失败"));
          });
      }
    },
    handleDefaultChange($index) {
      // 只有一个联系人，设置成非默认
      if (
        this.form.customerContacts.length === 1 &&
        this.form.customerContacts[0].isDefault === 0
      ) {
        this.$modal.msgWarning(this.$t("至少拥有一个默认联系人"));
        this.form.customerContacts[0].isDefault = 1;
        return;
      }

      // 设置默认联系人
      if (this.form.customerContacts[$index].isDefault === 1) {
        // 其他的置否
        let i = 0;
        this.form.customerContacts.forEach((e) => {
          if (i !== $index) {
            e.isDefault = 0;
          }
          i++;
        });
      } else {
        // 第一个置是
        this.form.customerContacts[0].isDefault = 1;
      }
    },
    cancel() {
      this.$tab.closePage();
      this.open = false;
      this.reset();
    },
    /** 提交按钮 */
    submitForm() {
      if (this.form.customerContacts.length === 0) {
        this.$modal.alert(this.$t("至少添加一位联系人"));
        return;
      }
      this.$refs["contactForm"].validate((valid1, err1) => {
        this.$refs["form"].validate((valid2, err2) => {
          this.$refs.bankForm.validate((valid3, err3) => {
            console.log(valid3, "valid3");
            if (!valid1 || !valid2 || !valid3) {
              this.$showFormValidateErrors({ ...err1, ...err2, ...err3 });
              return;
            }
            if (this.form.customerContacts.length === 0) {
              this.$modal.msgError(this.$t("至少填写一个联系人信息"));
              return;
            }
            if (this.form.competitorIds == 0) {
              this.$modal.msgError(this.$t("请重新选择主要竞争对手"));
              return;
            }

            // 重货标准和泡货标准，未打开就不传，提交前清空一下
            if (!this.showZhong) {
              this.form.weightUnit = null;
              this.zhongLines = [];
            }
            if (!this.showZhong1) {
              this.zhongLines = [];
            }
            if (!this.showPao) {
              this.form.lightUnit = null;
              this.paoLines = [];
            }
            if (!this.showPao1) {
              this.paoLines = [];
            }
            this.updateCustomerLines();
            const form = {
              ...this.form,
              type: this.form.type?.join(","),
              transportType: (this.form.transportType || [])?.join(","),
              taxRate: Number(this.form.taxRate),
              roles: (this.form.roles || [])?.join(","),
              pickupPoints: (this.form.pickupPoints || [])?.join(","),
              productIds: (this.form.productIds || [])?.join(","),
              busiCountryIds: (this.form.busiCountryIds || [])?.join(","),
              noConsignee: undefined,
              defaultPay: undefined,
              defaultBilling: undefined,
            };
            form.customerContacts = JSON.parse(
              JSON.stringify(this.form.customerContacts)
            );
            form.customerContacts.forEach((e) => {
              e.email = [...e.email].filter((i) => i !== "").join(",");
            });
            // 检查路线是否启用了但是没选择目的仓
            let errors = 0;
            form.customerLines.forEach((line) => {
              if (!line.objectiveIds || line.objectiveIds == "") {
                errors++;
              }
            });
            if (errors) {
              return this.$message.error("有两条路线未选择目的地");
            }
            //我的客户页面跳转直接，完善客户
            if (this.isCustomerServiceConfirmed) {
              form.isCustomerServiceConfirmed = this.isCustomerServiceConfirmed;
            }
            // 修改的提交
            if (this.form.id != null) {
              this.form.customerContacts.forEach((e) => {
                e.customerId = this.customerId;
              });

              console.log(this.form)
              if (this.$route.name === "perfect") {
                fillupCustomeInfo(form).then((r) => {
                  this.$modal.msgSuccess(this.$t("修改成功"));
                  this.open = false;
                  const obj = { path: "/customer/customer" };
                  this.$tab.closeOpenPage(obj);
                });
              } else {
                updateCustomer(form).then((response) => {
                  this.$modal.msgSuccess(this.$t("修改成功"));
                  this.open = false;
                  // this.getList();
                  const obj = { path: "/customer/customer" };
                  this.$tab.closeOpenPage(obj);
                });
              }

              return;
            }
            // 添加的提交
            createCustomer(form).then((response) => {
              this.$modal.msgSuccess(this.$t("新增成功"));
              this.open = false;
              // this.getList();
              const obj = { path: "/customer/customer" };
              this.$tab.closeOpenPage(obj);
            });
          });
        });
      });
    },
    /** 表单重置 */
    reset() {
      this.form = {
        inquiry: undefined,
        id: undefined,
        number: undefined,
        name: undefined,
        nameEn: undefined,
        level: 1,
        country: undefined,
        type: undefined,
        transportType: [],
        agentId: undefined,
        company: undefined,
        companyEn: undefined,
        payerName: undefined,
        address: undefined,
        productType: undefined,
        // productId: undefined,
        // pickupPoint: undefined,
        pickupPoints: [],
        productIds: [],
        memberId: undefined,
        birthday: undefined,
        balance: undefined,
        source: undefined,
        picture: undefined,
        customerService: undefined,
        customerContacts: [],
        customerLines: [],
        lightUnit: undefined,
        promoter: undefined,
        status: 1,
        founder: this.$store.getters.userId,
        department: undefined,
        invoiceTitle: undefined,
        licenseNumber: undefined,
        bank: undefined,
        bankNumber: undefined,
        project: undefined,
        billingAddress: undefined,
        billingTell: undefined,
        taxRate: undefined,
        remarks: undefined,
        arrivalConfirm: undefined,
        weightUnit: undefined,
        createTime: undefined,
        isShowTidanPrice: true,
        carName: undefined,
        carNo: undefined,
        customerBanks: [],
        isNew: true,// 业绩类型
        firstDealTime: undefined,// 首次成交时间
        // estimateEnterOpenSeaTime: undefined,// 掉入公海时间
        getMethod: undefined,// 获取方式
        createFrom: undefined,// 创建入口
        catchTime: undefined,//捞取时间
        customerServiceConfirmedTime: undefined,//归属时间
        updater: this.$store.getters.userId,// 更新人
        updateTime: undefined,// 更新时间
        roles: undefined,// 客户角色
        busiCountryIds: undefined,// 业务国家
        competitorIds: undefined,// 主要竞争对手
        weightYearly: undefined,// 年度发货量
        numYearly: undefined,// 年度发货次数
        noConsignee: false,// 控制无收货人
        defaultPay: false,// 默认付款
        defaultBilling: false,// 默认开票
      };
      this.form.createTime = new Date().getTime();
      this.form.updateTime = new Date().getTime();
      this.resetForm("form");
    },
    getCustomer(id) {
      return getCustomer(id).then((response) => {
        console.log(response, "response");
        this.form = {
          ...this.form,
          ...response.data,
          id: this.customerId,
          transportType:
            response.data.transportType && response.data.transportType !== ""
              ? response.data.transportType.split(",")
              : [],
          customerBanks: response.data.customerBankBackVOList,
          roles: response.data.roles? response.data.roles.split(",") : [],
          pickupPoints: this.stringArrToNumberArr(response.data.pickupPoints),
          productIds: this.stringArrToNumberArr(response.data.productIds),
          busiCountryIds: this.stringArrToNumberArr(response.data.busiCountryIds),
          competitorIds: Number(response.data.competitorIds)
        };
        if (this.form.productType) {
          console.log("1231", this.form.productType);
          this.getProductListFn(this.form.productType);
        }

        console.log(this.form)

        this.open = true;
        this.title = this.$t("修改客户");
        this.$forceUpdate()
        this.getZhongPao();
      });
    },
    stringArrToNumberArr(data) {
      if (data) {
        const strArr = data.split(",")
        const numArr = strArr.map(item => Number(item))
        return numArr
      } else {
        return []
      }
    },
    updateCustomerLines() {
      let zhongLines = [],
        paoLines = [];
      if (this.zhongLines.length > 0) {
        zhongLines = this.zhongLines;
      }
      if (this.paoLines.length > 0) {
        paoLines = this.paoLines;
      }
      this.form.customerLines = [...zhongLines, ...paoLines];
    },
    handleAddContact() {
      this.form.customerContacts.push({
        areaCode: "",
        // "customerId": 0,q
        department: "",
        email: [""],
        isDefault: this.form.customerContacts.length === 0 ? 1 : 0,
        name: "",
        phoneNew: "",
        position: "",
        social: undefined,
        socialNumber: "",
        userid: undefined,
        nameEn: "",
        // "username": ""
      });
    },
    handleDeleteContact($index) {
      this.form.customerContacts.splice($index, 1);
      if (this.form.customerContacts.length > 0) {
        this.$refs["contactForm"].clearValidate();

        if (!this.form.customerContacts.find((e) => e.isDefault)) {
          this.form.customerContacts[0].isDefault = 1;
        }
      }
    },
    getZhongPao() {
      getZhongPaoBest({
        customerId: this.customerId,
        // departureId: this.departureId,
        // objectiveId: this.objectiveId
      }).then((r) => {
        if (!this.form.weightUnit) this.form.weightUnit = r.data.zhongEdge;
        if (!this.form.lightUnit) this.form.lightUnit = r.data.paoEdge;
      });
    },
    getCompetitorList() {
      competitorListAll().then((r) => {
        this.competitorList = r.data;
      })
    },
    changeCompetitor(val) {
      if (val == 0) {
        this.$prompt("请输入主要竞争对手", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        }).then((data) => {
          console.log(data)
          addCompetitor({
            name: data.value
          }).then(_ => {
            this.$message.success('添加成功！')
            this.getCompetitorList()
          })
        })
      }
    }
  },
  computed: {
    isChinese() {
      return this.$i18n.locale === "zh_CN";
    },
    userId() {
      return this.$store.state.user.id;
    },
    customerId() {
      return this.$route.params.customerId;
    },
    /* userMemberUser(){
     let list = this.memberList.filter(item => {
        return this.selectMemberList.findIndex(i => i.id === item.id) < 0
      })
      return [...this.selectMemberList,...list]
    }, */
    productListFilter() {
      return this.productList.filter((p) => p.typeId === this.form.productType);
    },
    customerSelectFn() {
      if (this.recommended.length > 0) {
        let i = this.customerSelect.find(
          (item) => item.id === this.recommended[0].id
        );
        if (!i) {
          this.customerSelect.push(this.recommended[0]);
        }
        return this.customerSelect;
      } else {
        return this.customerSelect;
      }
    },
  },
  watch: {
    zhongLines() {
      console.log("zhongLines", this.zhongLines);
      this.updateCustomerLines();
    },
    paoLines() {
      console.log("paoLines", this.paoLines);
      this.updateCustomerLines();
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-table__cell {
  padding-bottom: 0;
  .cell {
    .el-form-item {
      margin-bottom: 9px;
    }

    .el-form-item__error {
      z-index: 1;
      padding-top: 0;
      top: 32px;
    }
  }
}
.title-text {
  font-size: 18px; 
  color: #111;
}
</style>
