<template>
  <div class="customer-merge">
    <el-dialog append-to-body :title="$t('合并客户')" :visible.sync="dialogVisible" width="900px">
      <el-form ref="form" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>{{ $t('保留客户') }}</span>
                <el-button type="success" size="small" style="float: right" @click="selectCustomer(1)">
                  {{ $t('请选择') }}
                </el-button>
              </div>
              <el-form-item :label="$t('客户编号')+':'">
                {{ retainCustomer.number }}
              </el-form-item>
              <el-form-item :label="$t('客户名称')+':'">
                {{ $l(retainCustomer, "name") }}
              </el-form-item>
              <el-form-item :label="$t('客户经理')+':'">
                {{ retainCustomer.customerServiceName }}
              </el-form-item>
              <el-form-item :label="$t('创建时间')+':'">
                {{ parseTime(retainCustomer.createTime) }}
              </el-form-item>
              <el-form-item :label="$t('联系方式')+':'">
                +{{ retainCustomer.defaultContactPhone }}
              </el-form-item>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>{{ $t('​被合并客户-非主客户') }}</span>
                <el-button type="success" size="small" style="float: right" @click="selectCustomer(2)">
                  {{ $t('请选择') }}
                </el-button>
              </div>
              <el-form-item :label="$t('客户编号')+':'">
                {{ mergeCustomer.number }}
              </el-form-item>
              <el-form-item :label="$t('客户名称')+':'">
                {{ $l(mergeCustomer, "name") }}
              </el-form-item>
              <el-form-item :label="$t('客户经理')+':'">
                {{ mergeCustomer.customerServiceName }}
              </el-form-item>
              <el-form-item :label="$t('创建时间')+':'">
                {{ parseTime(mergeCustomer.createTime) }}
              </el-form-item>
              <el-form-item :label="$t('联系方式')+':'">
                +{{ mergeCustomer.defaultContactPhone }}
              </el-form-item>
            </el-card>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">{{ $t('确 定') }}</el-button>
        <el-button @click="dialogVisible = false">{{ $t('取 消') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog append-to-body :title="$t('选择客户')" :visible.sync="customerDialogVisible"
               :close-on-click-modal="false" width="80%">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="100px">
        <el-form-item :label="$t('客户编号')" prop="number">
          <el-input
            v-model.trim="queryParams.number"
            :placeholder="$t('请输入客户编号')"
            clearable
            @keyup.enter.native="handleQuery"
            @input="queryParams.number=queryParams.number.replace(/\s+/g, '')"
          />
        </el-form-item>
        <el-form-item :label="$t('客户名称')" prop="name">
          <el-input
            v-model.trim="queryParams.name"
            :placeholder="$t('请输入客户名称')"
            clearable
            @keyup.enter.native="handleQuery"
            @input="queryParams.name=queryParams.name.replace(/\s+/g, '')"
          />
        </el-form-item>
        <el-form-item :label="$t('区号')">
          <el-select
            v-model="queryParams.areaCode"
            :placeholder="$t('请选择区号')"
          >
            <el-option
              v-for="(item, index) in countryList"
              :key="index"
              :label="
                item.nameShort +
                (isChinese ? item.nameZh : item.nameEn) +
                ' +' +
                item.tel
              "
              :value="item.tel"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('联系方式')">
          <el-input
            :placeholder="$t('请输入联系方式')"
            v-model.trim="queryParams.defaultContactPhone"
            @input="queryParams.defaultContactPhone=queryParams.defaultContactPhone.replace(/\s+/g, '')"
          ></el-input>
        </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>
      <el-table :data="list" v-loading="loading" border size="mini">
        <el-table-column align="center" width="80">
          <template slot-scope="{row}">
            <el-radio v-model="customerId" :label="row.id">&nbsp;</el-radio>
          </template>
        </el-table-column>
        <el-table-column :label="$t('客户编号')" align="center">
          <template slot-scope="{ row }">
<!--            <el-link type="primary" @click.native="$router.push('/customer/query/' + row.id)">{{ row.number }}</el-link>-->
            {{ row.number }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('客户名称')" align="center">
          <template slot-scope="{ row }">
            <p style="display: inline-block; white-space: pre-wrap">
              {{ $l(row, "name") }}
            </p>
            <el-tag v-if="row.isInOpenSea" size="mini">{{ $t("公") }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('主联系人')"
          prop="defaultContactName"
        ></el-table-column>
        <el-table-column :label="$t('主联系方式')" prop="defaultContactPhone">
          <template v-slot="{ row }">
            +{{ row.defaultContactPhone }} <br/>
            <contacts :id="row.id">
              <el-button type="text">更多</el-button>
            </contacts>
          </template>
        </el-table-column>
        <el-table-column :label="$t('客户类别')" align="center">
          <template slot-scope="{ row }">
            {{ getDictDatas2(DICT_TYPE.CUSTOMER_TYPE, (row.type||'').split(',')).map(e => isChinese ? e.label : e.labelEn).join(', ')}}
<!--            <dict-tag-->
<!--              :type="DICT_TYPE.CUSTOMER_TYPE"-->
<!--              :value="scope.row.type"-->
<!--            />-->
          </template>
        </el-table-column>
        <el-table-column :label="$t('角色')" align="center">
          <template slot-scope="{ row }">
            {{ getDictDatas2(DICT_TYPE.CUSTOMER_ROLE, (row.roles || '').split(',')).map(e => isChinese ? e.label : e.labelEn).join(', ') }}
            <!--            <dict-tag-->
            <!--              :type="DICT_TYPE.CUSTOMER_ROLE"-->
            <!--              :value="scope.row.roles"-->
            <!--            />-->
          </template>
        </el-table-column>
        <el-table-column :label="$t('客户经理')" align="center" prop="customerServiceName"></el-table-column>
        <el-table-column :label="$t('国籍')" align="center" prop="country"
                         :formatter="countryFormatter"></el-table-column>
        <el-table-column :label="$t('出货渠道')" align="center">
          <template slot-scope="{ row }">
            {{ channel(row.transportType) }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('客户来源')">
          <template slot-scope="scope">
            <dict-tag
              :type="DICT_TYPE.CUSTOMER_SOURCE"
              :value="scope.row.source"
            />
          </template>
        </el-table-column>
        <el-table-column :label="$t('业务国家')">
          <template slot-scope="{ row }">
            {{ getBusiCountryNames(row.busiCountryIds) }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('常用提货网点')">
          <template slot-scope="{ row }">
            {{ getPickupPointNames(row.pickupPoints) }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('年度发货量')" align="center">
          <template slot-scope="{ row }">
            {{ row.weightYearly }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('主营类别')">
          <template slot-scope="{ row }">
            {{ getProductTypeNames(row.productType) }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('主要竞争对手')" prop="competitorNames">
        </el-table-column>
        <el-table-column :label="$t('年度发货次数')" align="center">
          <template slot-scope="{ row }">
            {{ row.numYearly }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('推介人')">
          <template slot-scope="{ row }">
            {{ getPromoterName(row.promoter) }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('入公海时间')" align="center" width="160">
          <template v-slot="{ row }">
            {{ parseTime(row.enterOpenSeaTime ? row.enterOpenSeaTime : row.estimateEnterOpenSeaTime) }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('入仓确认')" align="center">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.arrivalConfirm == 1">{{ $t('是') }}</el-tag>
            <el-tag type="info" v-else>{{ $t('否') }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('控货无收货人')" align="center">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.noConsignee">{{ $t('是') }}</el-tag>
            <el-tag type="info" v-else>{{ $t('否') }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('默认付款')" align="center">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.defaultPay">{{ $t('是') }}</el-tag>
            <el-tag type="info" v-else>{{ $t('否') }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('归属时间')" width="160" align="center">
          <template slot-scope="scope">
            {{ parseTime(scope.row.customerServiceConfirmedTime) }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('首次成交时间')" width="160" align="center">
          <template slot-scope="scope">
            {{ parseTime(scope.row.firstDealTime) }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('获取方式')" align="center">
          <template slot-scope="scope">
            <dict-tag
              :type="DICT_TYPE.CUSTOMER_GET_METHOD"
              :value="scope.row.getMethod"
            />
          </template>
        </el-table-column>
        <el-table-column :label="$t('创建人')" prop="createUsername" align="center">
        </el-table-column>
        <el-table-column :label="$t('创建时间')" align="center" width="160">
          <template slot-scope="scope">
            {{ parseTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('最后更新时间')" align="center" width="160">
          <template slot-scope="scope">
            {{ parseTime(scope.row.updateTime) }}
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                  @pagination="getList"/>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirm">{{ $t('确 定') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getCustomerPage, customerMergeCus} from "@/api/ecw/customer"
import {getDictDatas, DICT_TYPE, getDictDatas2} from "@/utils/dict"
import Contacts from "./contacts.vue";
import Template from "@/views/cms/template/index.vue";
import {getProductTypeList} from "@/api/ecw/productType";

export default {
  name: "CustomerMerge",
  components: {
    Template,
    Contacts
  },
  data() {
    return {
      dialogVisible: false,
      getDictDatas,
      getDictDatas2,
      DICT_TYPE,
      loading: false,
      customerId: null,
      customerDialogVisible: false,
      queryParams: {
        pageNo: 1,
        pageSize: 10
      },
      list: [],
      total: 0,
      type: 1,
      retainCustomer: {},
      mergeCustomer: {},
    }
  },
  props: {
    countryList: {
      type: Array,
      default: () => []
    },
    getNodeLists: {
      type: Array,
      default: () => []
    },
    productTypeList: {
      type: Array,
      default: () => []
    },
    customerSelectFn: {
      type: Array,
      default: () => []
    }
  },
  computed: {
    isChinese() {
      return this.$i18n.locale === "zh_CN";
    },
    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(",")
          : "";
      };
    },
    getBusiCountryNames() {
      return (ids) => {
        if (ids) {
          const idsArr = ids.split(',')
          const strArr = []
          this.countryList.forEach(item => {
            if (idsArr.includes(item.id.toString())) {
              strArr.push(this.isChinese ? item.nameZh : item.nameEn)
            }
          })
          return strArr.length > 0 ? strArr.join(',') : null
        } else {
          return null
        }
      }
    },
    getPickupPointNames() {
      return (ids) => {
        if (ids) {
          const idsArr = ids.split(',')
          const strArr = []
          this.getNodeLists.forEach(item => {
            if (idsArr.includes(item.id.toString())) {
              strArr.push(this.isChinese ? item.titleZh : item.titleEn)
            }
          })
          return strArr.length > 0 ? strArr.join(',') : null
        } else {
          return null
        }
      }
    },
    getProductTypeNames() {
      return (ids) => {
        if (ids) {
          const idsArr = ids.toString().split(',')
          const strArr = []
          this.productTypeList.forEach(item => {
            if (idsArr.includes(item.id.toString())) {
              strArr.push(this.isChinese ? item.titleZh : item.titleEn)
            }
          })
          return strArr.length > 0 ? strArr.join(',') : null
        } else {
          return null
        }
      }
    },
    getPromoterName() {
      return (id) => {
        if (id) {
          let strName = ''
          for (const item of this.customerSelectFn) {
            if (item.id == id) {
              strName = item.name
              break
            }
          }
          return strName
        } else {
          return null
        }
      }
    }
  },
  created() {
    this.getList();
  },
  methods: {
    init() {
      this.retainCustomer = {}
      this.mergeCustomer = {}
    },
    selectCustomer(type) {
      this.type = type
      this.customerId = null
      this.queryParams = {
        pageNo: 1,
        pageSize: 10
      }
      this.customerDialogVisible = true
      this.getList();
    },
    handleSubmit() {
      if (!this.retainCustomer.id) {
        this.$message.error(this.$t("请选择保留客户"))
        return
      }
      if (!this.mergeCustomer.id) {
        this.$message.error(this.$t("请选择被合并客户"))
        return
      }
      if (this.mergeCustomer.id == this.retainCustomer.id) {
        this.$message.success(this.$t("保留客户和非主客户不能为同一客户"))
        return
      }
      this.$confirm('保留客户和非主客户,不能在两个不同的客户经理名下,请先确认两个客户在同一个客户经理名下,不允许提交当非主客户/保留客户在移交过程中,不允许合并?', '提示', {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消')
      }).then(() => {
        this.submitData()
      })
    },
    submitData() {
      const h = this.$createElement;
      this.$msgbox({
        title: '注意事项',
        message: h('div', {class: 'stips'}, [
          h('p', null, '1. 保留客户和非主客户,不能在两个不同的客户经理名下,请先确认两个客户在同一个客户经理名下'),
          h('p', null, '2. 被合并客户,提交后会直接删除'),
          h('p', null, '3. 合并后,非主客户的联系人,跟进记录,报价单,订单,客户投诉,品牌授权都迁移到保留客户中,其他信息不会迁移,如需要维护非主客户的客户档案信息到保留客户中,请先维护好再操作'),
        ]),
        showCancelButton: true,
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消')
      }).then(action => {
        if (action == 'confirm') {
          customerMergeCus({
            customerIdDeleted: this.mergeCustomer.id,
            customerIdSaved: this.retainCustomer.id
          }).then(_ => {
            this.$message.success(this.$t("操作成功"))
            this.dialogVisible = false
            this.$emit('refresh')
          })
        }
      })
    },
    confirm() {
      if (this.customerId) {
        for (const row of this.list) {
          if (row.id == this.customerId) {
            if (this.type == 1) {
              this.retainCustomer = row
            } else {
              this.mergeCustomer = row
            }
            break
          }
        }
        this.customerDialogVisible = false
      } else {
        this.$message.error(this.$t("请选择客户"))
      }
    },
    countryFormatter(row, column, cellValue) {
      const country = this.countryList.find((e) => e.id === cellValue);
      return this.isChinese ? country?.nameZh : country?.nameEn;
    },
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNo: 1,
        pageSize: 10
      }
      this.getList();
    },
    getList() {
      this.loading = true;
      getCustomerPage(this.queryParams).then((response) => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    }
  }
}
</script>