<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      label-width="100px"
    >
      <el-form-item :label="$t('跟进类型')">
        <dict-selector
          clearable
          :type="DICT_TYPE.CUSTOMER_TYPE"
          v-model="queryParams.followType"
          @change="handleQuery"
        ></dict-selector>
      </el-form-item>
      <el-form-item :label="$t('跟进方式')">
        <dict-selector
          clearable
          :type="DICT_TYPE.CUSTOMER_FOLLOWUP_METHOD"
          v-model="queryParams.followMethod"
          @change="handleQuery"
        ></dict-selector>
      </el-form-item>
      <el-form-item :label="$t('客户经理')" prop="customerService">
        <el-select
          multiple
          clearable
          v-model="queryParams.customerService"
          :placeholder="$t('请选择客户经理')"
          size="small"
          @change="handleQuery"
        >
          <el-option
            v-for="dict in customerServiceList"
            :key="dict.id"
            :label="dict.nickname"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('跟进结果')">
        <el-select
          clearable
          v-model="queryParams.resultType"
          :placeholder="$t('请选择')"
          size="small"
          @change="handleQuery"
        >
          <el-option
            v-for="dict in getDictDatas(DICT_TYPE.CUSTOMER_FOLLOWUP_RESULT_TYPE)"
            :key="dict.value"
            :label="isChinese ? dict.label : dict.labelEn"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('跟进状态')">
        <el-select
          multiple
          clearable
          v-model="queryParams.status"
          :placeholder="$t('请选择')"
          size="small"
          @change="handleQuery"
        >
          <el-option
            v-for="dict in getDictDatas(DICT_TYPE.CUSTOMER_FOLLOWUP_STATUS)"
            :key="dict.value"
            :label="isChinese ? dict.label : dict.labelEn"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('跟进时间')">
        <el-date-picker
          type="datetimerange"
          clearable
          v-model="dateRangeCreateTime"
          style="width: 320px"
          value-format="yyyy-MM-dd HH:mm:ss"
          range-separator="-"
          :start-placeholder="$t('开始跟进时间')"
          :end-placeholder="$t('结束跟进时间')"
        />
      </el-form-item>
      <el-form-item :label="$t('下次跟进时间')">
        <el-date-picker
          type="datetimerange"
          clearable
          v-model="dateRangeCreateTime"
          style="width: 320px"
          value-format="yyyy-MM-dd HH:mm:ss"
          range-separator="-"
          :start-placeholder="$t('开始下次跟进时间')"
          :end-placeholder="$t('结束下次跟进时间')"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">{{
          $t("搜索")
        }}</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">{{
          $t("重置")
        }}</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <div
      v-if="path === '/customer/customer'"
      style="color: red; margin-bottom: 5px"
    >
      注意：创建的客户需接收
    </div>
    <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="[selectAuthorityFn('ecw:customer:follow-create')]"
          >{{ $t("新增") }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="[selectAuthorityFn('ecw:customer:follow-export')]"
          >{{ $t("导出") }}</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="[selectAuthorityFn('ecw:customer:follow-modify-status')]"
          :disabled="!selectCustomerList.length"
          @click="setFullContainerLoad(true)"
          type="primary"
          plain
          size="mini"
          :loading="exportLoading"
          >{{ $t("修改状态") }}</el-button
        >
      </el-col>
    </el-row>

    <!-- 列表 -->
    <el-table
      ref="multipleTable"
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column :label="$t('编号')" align="center" prop="number">
        <template v-slot="{ row }">
          {{ row.number }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('跟进类型')" align="center">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.CUSTOMER_FOLLOWUP_TYPE" :value="scope.row.followType" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('报价单')" align="center" prop="offerId"></el-table-column>
      <el-table-column :label="$t('客户编号')" align="center" prop="customerId"></el-table-column>
      <el-table-column :label="$t('客户经理')" align="center" prop="customerServiceName"></el-table-column>
      <el-table-column :label="$t('目的')" align="center" prop="purpose"></el-table-column>
      <el-table-column :label="$t('跟进方式')" align="center">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.CUSTOMER_FOLLOWUP_METHOD" :value="scope.row.followMethod" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('跟进结果')" align="center">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.CUSTOMER_FOLLOWUP_RESULT_TYPE" :value="scope.row.resultType" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('跟进时间')" align="center">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.beginFollowTime) }}~{{ parseTime(scope.row.endFollowTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('下次跟进计划')" align="center" prop="nextPlan"></el-table-column>
      <el-table-column :label="$t('下次跟进时间')" align="center">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.beginNextTime) }}~{{ parseTime(scope.row.endNextTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('创建人')" align="center" prop="creatorName"></el-table-column>
      <el-table-column :label="$t('创建时间')" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column width="200px" :label="$t('操作')" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="[selectAuthorityFn('ecw:customer:follow-update')]"
            >{{ $t("编辑") }}</el-button
          >
          <el-button
            size="mini"
            v-has-permi="[selectAuthorityFn('ecw:customer:follow-add-plan')]"
            type="text"
            icon="el-icon-collection"
            @click="followUp(scope.row)"
            >{{ $t("增加计划") }}</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

  </div>
</template>

<script>
import {
  createCustomer,
  updateCustomer,
  deleteCustomer,
  getCustomer,
  getCustomerPage,
  exportCustomerExcel,
  testEnterToOpenSea,
  getCustomerDeptPage,
  changeCustomerAir,
  getPotential,
  setChangeCustomerFcl,
  potentialExportExcel,
  deptExportExcel,
  recycleUnconfirmedCustomer,
  updatecustomerToOld,
} from "@/api/ecw/customer";
import { getDictDatas, DICT_TYPE } from "@/utils/dict";
import { CommonStatusEnum } from "@/utils/constants";
import { uploadFile } from "@/api/infra/file";
import upload from "@/components/ImageUpload";
import { getNodeList } from "@/api/ecw/node";
import CustomerFollowList from "@/components/CustomerFollowList";
import customerComplaints from "@/components/customerComplaints";
import { listServiceUser } from "@/api/system/user";
import { getCountryListAll } from "@/api/ecw/country";
import { getCreditPage } from "@/api/customer/credit";
import { customerExportExcel, changeCustomerDefaultPay, changeCustomerNoConsignee,changeCustomerDefaultBilling} from "@/api/ecw/customer";
import transferCustomer from "@/views/ecw/customer/transferCustomer";
import Template from "@/views/cms/template/index.vue";
import AddPotentialCustom from "@/views/ecw/customer/addPotentialCustom.vue";
import Contacts from "@/views/ecw/customer/components/contacts.vue";
import { getUserProfile } from "@/api/system/user";

import AreaCodeSelector from "@/components/AreaCodeSelector/index.vue";
import {getCustomerFollowList} from "@/api/ecw/customerFollow";

export default {
  name: "EcwCustomerIndex",
  components: {
    Contacts,
    AddPotentialCustom,
    Template,
    upload,
    CustomerFollowList,
    customerComplaints,
    transferCustomer,
    AreaCodeSelector
  },
  data() {
    return {
      env: process.env.NODE_ENV,
      getDictDatas,
      DICT_TYPE,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 客户列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dateRangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        number: null,
        name: null,
        level: null,
        source: null,
        customerService: null,
        status: null,
        department: null,
        creditLevel: null,
        country: null,
        resourceType: null,
        memberCode: null,
        memberName: null,
        memberMobile: null,
        memberAreaCode: null
      },
      // 表单参数
      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: true,
            message: this.$t("客户经理不能为空"),
            trigger: "blur",
          },
        ],
        status: [
          {
            required: true,
            message: this.$t("客户状态不能为空"),
            trigger: "blur",
          },
        ],
        founder: [
          {
            required: true,
            message: this.$t("创建人不能为空"),
            trigger: "blur",
          },
        ],
      },
      // 网点
      nodeList: [],
      showLine: false,
      customerId: undefined,
      customerServiceList: [],
      countryList: [],
      creditList: [],
      selectCustomerList: [],
      transferShow: false,
      dialogVisible: false,
      customData: {},
      currentisNew: false,
      userId: undefined, //lanbm 2024-05-23 add
    };
  },
  computed: {
    path() {
      return this.$route.path;
    },
    channel() {
      return (val) => {
        return !!val
          ? this.getDictDatas(this.DICT_TYPE.ECW_CUSTOMER_TRANSPORT_TYPE)
              .filter((i) => (val.split(",") || []).includes(i.value))
              .map((i) => (this.isChinese ? i.label : i.labelEn))
              .join("，")
          : "";
      };
    },
    isChinese() {
      return this.$i18n.locale === "zh_CN";
    },
    authorityFn() {
      let i = "";
      switch (this.$route.path) {
        case "/customer/department-customers":
          i = "dep-";
          break;
        case "/customer/potential":
          i = "pot-";
          break;
      }
      return i;
    },
    selectAuthorityFn() {
      return (val) => {
        let t = val.split(":");
        t[t.length - 1] = this.authorityFn + t[t.length - 1];
        console.log(t.join(":"));
        return t.join(":");
      };
    },
  },
  watch: {
    selectCustomerList(val) {
      if (val.length === 0) {
        this.getList();
        this.$refs.multipleTable.clearSelection();
      }
    },
  },
  created() {
    this.getList();
    listServiceUser().then((r) => {
      this.customerServiceList = r.data;
    });
  },
  activated() {
    this.getList();
  },
  methods: {
    handleMergeCus() {
      //合并客户
    },
    recovery(row) {
      this.$confirm(this.$t("是否要回收当前{name}", row), "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          recycleUnconfirmedCustomer({ customerId: row.id }).then((r) => {
            this.$message.success(this.$t("回收成功。"));
            this.getList();
          });
        })
        .catch(() => {
          this.$message.info(this.$t("已取消"));
        });
    },
    // 设置整柜
    setFullContainerLoad(isFcl) {
      setChangeCustomerFcl({
        customerIdList: this.selectCustomerList,
        isFcl,
      }).then((r) => {
        if (r.code === 0) {
          this.$message.success(
            isFcl ? "设置客户为海运整柜成功！" : "设置客户为非海运整柜成功！"
          );
          this.selectCustomerList = [];
          this.getList();
        }
      });
    },
    // 设置空运客户
    setChangeCustomerAir(isAir) {
      changeCustomerAir({
        customerIdList: this.selectCustomerList,
        isAir,
      }).then((r) => {
        console.log(r);
        if (r.code === 0) {
          this.$message.success(
            isAir ? "设为空运客户成功！" : "设为非空运客户成功！"
          );
          this.selectCustomerList = [];
          this.getList();
        }
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    complaint(row) {
      this.customerId = row.id;
      this.$nextTick(() => {
        this.$refs.customerComplaints.handleAdd();
      });
    },
    countryFormatter(row, column, cellValue) {
      const country = this.countryList.find((e) => e.id === cellValue);
      return this.isChinese ? country?.nameZh : country?.nameEn;
    },
    delay(row) {
      this.$router.push({ path: "/customer/delay", query: { id: row.id } });
    },
    followUp(row) {
      this.customerId = row.id;
      this.$nextTick(() => {
        this.$refs.CustomerFollowList.customerFollow.dialogVisible = true;
      });
    },
    //报价
    quote(row) {
      //lanbm 2024-05-23 添加报价是判断客户所属客户经理，不是就不能报价
      if (row.customerService != this.userId) {
        this.$message.error(this.$t("此客户属于其他客户经理名下的客户。"));
        return;
      }
      //this.$router.push({path:'/offer/create',query:{id:row.id}})
      this.$router
        .push({ path: "/offer/create", query: { customer: row, type: 1 } })
        .then({
          //this.$refs.push({path:'/customer-contacts/select',query:{pageNo:1,pageSize:10,searchKey:row.defaultContactPhone}})
        });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 处理查询参数
      let params = { ...this.queryParams };
      this.addBeginAndEndTime(
        params,
        this.dateRangeCreateTime,
        "createTime",
        false
      );
      // 执行查询
      getCustomerFollowList(params).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push("/customer/follow-add-edit/0");
      // this.reset();
      // this.open = true;
      // this.title = this.$t("添加客户");
    },
    // 新增潜在客户
    handleAddPotential() {
      this.$refs.potentialCustom.dialogTableVisible = true;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      const name = row.name;
      const number = row.number;
      this.$modal
        .confirm(
          this.$t('是否确认删除客户编号为"') + number + this.$t('"的数据项?')
        )
        .then(function () {
          return deleteCustomer(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t("删除成功"));
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      let func = null;
      let title = "";
      switch (this.$route.path) {
        case "/customer/customer":
          func = customerExportExcel;
          title = "是否确认导出所有客户数据项?";
          break;
        case "/customer/department-customers":
          func = deptExportExcel;
          title = "是否确认导出部门客户数据项?";
          break;
        case "/customer/potential":
          func = potentialExportExcel;
          title = "是否确认导出潜在客户数据项?";
          break;
      }

      // // 执行导出
      this.$modal
        .confirm(this.$t(title))
        .then(() => {
          func().then((r) => {
            this.$message.success(
              this.$t("已加入导出队列，请稍后在下载日志中下载")
            );
          });
        })
        .catch(() => {});
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    handleSelectionChange(val) {
      this.selectCustomerList = val.map((i) => i.id);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(row.id);
      this.$router.push("/customer/add-edit/" + row.id);
      // this.reset();
      // const id = row.id;
      // getCustomer(id).then(response => {
      //   this.form = { ...this.form, ...response.data };
      //   this.open = true;
      //   this.title = this.$t("修改客户");
      // });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.$router.push("/customer/query/" + row.id);
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        number: undefined,
        name: undefined,
        level: undefined,
        country: undefined,
        type: undefined,
        agentId: undefined,
        company: undefined,
        address: undefined,
        productType: undefined,
        productId: undefined,
        pickupPoint: undefined,
        memberId: undefined,
        birthday: undefined,
        balance: undefined,
        source: undefined,
        picture: undefined,
        customerService: undefined,
        customerContacts: [],
        customerLines: [],
        promoter: undefined,
        status: undefined,
        founder: undefined,
        department: undefined,
        invoiceTitle: undefined,
        licenseNumber: undefined,
        bank: undefined,
        bankNumber: undefined,
        project: undefined,
        billingAddress: undefined,
        billingTell: undefined,
        taxRate: undefined,
        remarks: undefined,
        arrivalConfirm: undefined,
        weightUnit: undefined,
      };
      this.resetForm("form");
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeCreateTime = [];
      this.resetForm("queryForm");
      this.queryParams = {
        pageNo: 1,
        pageSize: 10,
        number: null,
        name: null,
        level: null,
        source: null,
        customerService: null,
        status: null,
        department: null,
        creditLevel: null,
        country: null,
        memberCode: null,
        memberName: null,
        memberMobile: null,
        memberAreaCode: null
      };
      this.handleQuery();
    },
    /** 调入公海池测试用 */
    seasPond(row) {
      testEnterToOpenSea(row.id).then((r) => {
        if (r.code === 0) {
          this.$t("调入公海池成功！");
          this.getList();
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          // return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateCustomer(this.form).then((response) => {
            this.$modal.msgSuccess(this.$t("修改成功"));
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createCustomer(this.form).then((response) => {
          this.$modal.msgSuccess(this.$t("新增成功"));
          this.open = false;
          this.getList();
        });
      });
    },
    // 修改客户类型
    modifyCustomer() {
      this.$confirm(
        this.$t("修改业绩类型后，将会影响客户新订单业绩计算，请问确定吗？"),
        this.$t("提示"),
        {
          confirmButtonText: this.$t("确定"),
          cancelButtonText: this.$t("取消"),
          type: "warning",
        }
      )
        .then(() => {
          updatecustomerToOld({
            customerId: this.customData.id,
            isNew: this.currentisNew,
          }).then((r) => {
            this.$message.success(this.$t("修改成功"));
            this.dialogVisible = false;
            this.getList();
          });
        })
        .catch(() => {});
    },
    setDefaultPay() {
      changeCustomerDefaultPay({
        customerIdList: this.selectCustomerList,
        defaultPay: true
      }).then(_ => {
        this.$message.success(this.$t("操作成功"))
        this.getList()
      })
    },
    setNoConsignee() {
      changeCustomerNoConsignee({
        customerIdList: this.selectCustomerList,
        noConsigee: true
      }).then(_ => {
        this.$message.success(this.$t("操作成功"))
        this.getList()
      })
    },
    setDefaultBilling() {
      changeCustomerDefaultBilling({
        customerIdList: this.selectCustomerList,
        defaultBilling: true
      }).then(_ => {
        this.$message.success(this.$t("操作成功"))
        this.getList()
      })
    }
  },
};
</script>
