<!--
@name: 客户管理
@author: 张泽贤
@time: 2022-08-01
@doc: PROLOG_UPCloudSolutionForTMS__v1.2.1_基础数据_1.2.1.doc
-->
<template>
  <div class="pages">
    <p-spin :spinning="spinning" v-if="!editType" v-show="!addressAnalysisShow">
      <p-card style="margin-bottom: 10px">
        <p-form-model ref="formTarget" :model="form" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" class="plg-grid-from">
          <a-row>
            <a-col :span="6">
              <p-form-model-item label="客户编码">
                <p-input v-model="form.customerCode" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="客户名称">
                <p-input v-model="form.customerName" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="所属货主">
                <p-input v-model="form.cargoOwnerName" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item :wrapper-col="{ span: 24 }" style="text-align: right">
                <a-space>
                  <p-button type="primary" @clickSync="onSearch" icon="search">查询</p-button>
                  <p-button @click="onReset">重置</p-button>
                  <!-- <p-button type="primary" @click="onSeniorSearch">高级查询</p-button> -->
                </a-space>
              </p-form-model-item>
            </a-col>
          </a-row>
        </p-form-model>
      </p-card>
      <p-card title="客户信息" style="margin-bottom: 10px">
        <a-space slot="extra">
          <p-button type="primary" @click="onEdit({}, 'add')" v-action:add>新增</p-button>
          <p-button type="primary" @click="onEnOrDis(10)" :disabled="!selectedRowKeys.length" v-action:status>启用</p-button>
          <p-button type="danger" @click="onEnOrDis(0)" :disabled="!selectedRowKeys.length" v-action:status>停用</p-button>
          <p-button type="danger" @click="onDel" :disabled="!selectedRowKeys.length" v-action:del>删除</p-button>
          <p-button type="primary" @click="onAddressAnalysis" :disabled="!selectedRowKeys.length" v-action:mapParse>地址解析</p-button>
          <import-Button :importUrl="importUrl" :tmpUrl="downUrl" fileName="客户模板" />
        </a-space>
        <t-table
          ref="masterTable"
          dragle
          bordered
          :extendedObjectCode="'4'"
          row-key="id"
          :id="$route.meta.menuId + '_customer'"
          :scroll="{ x: true }"
          :vScrollX="{enabled:true}"
          :vScrollY="{enabled:true,rows:10}"
          :data-source="dataSource"
          :remote-url="listRemoteUrl"
          :remoteData="listParams"
          :rowSelectType="2"
          rowSelectFixed
          @clickRow="masterClickRow"
          @selectChange="selectChange"
        >
          <t-table-column data-index="code" title="客户编码" :width="120" />
          <t-table-column data-index="name" title="客户名称" :width="120" />
          <t-table-column data-index="shortName" title="客户简称" :width="120" />
          <t-table-column data-index="departmentName" title="部门" :width="120" />
          <t-table-column data-index="cooperativeNatureName" title="合作性质" :width="120" />
          <t-table-column data-index="statusName" title="状态" :width="120" />
          <t-table-column data-index="taxRegisterNumber" title="税务登记号" :width="120" />
          <t-table-column data-index="businessLicenseNumber" title="营业执照号" :width="120" />
          <t-table-column data-index="roadPermit" title="道路许可证" :width="120" />
          <t-table-column data-index="cargoOwnerName" title="所属货主" :width="120" />
          <t-table-column data-index="memo" title="备注" :width="120" />
          <t-table-column data-index="contact" title="联系人" :width="120" />
          <t-table-column data-index="phoneNumber" title="手机号" :width="120" />
          <t-table-column data-index="landlineNumber" title="座机号" :width="120" />
          <t-table-column data-index="email" title="邮箱" :width="120" />
          <t-table-column data-index="postCode" title="邮编" :width="120" />
          <t-table-column data-index="provinceName" title="省" :width="120" />
          <t-table-column data-index="cityName" title="市" :width="120" />
          <t-table-column data-index="districtName" title="区" :width="120" />
          <t-table-column data-index="address" title="详细地址" :width="120" />
          <t-table-column data-index="longitude" title="经度" :width="120" />
          <t-table-column data-index="latitude" title="纬度" :width="120" />
          <t-table-column data-index="legalman" title="法人代表" :width="120" />
          <t-table-column data-index="invoice" title="发票抬头" :width="120" />
          <t-table-column data-index="invoiceTaxNumber" title="税号" :width="120" />
          <t-table-column data-index="registeredCapital" title="注册资金" :width="120" />
          <t-table-column data-index="bankName" title="开户行" :width="120" />
          <t-table-column data-index="bankAccount" title="银行账号" :width="120" />
          <t-table-column data-index="established" title="成立时间" :width="120" />
          <t-table-column data-index="registeredAddress" title="注册地址" :width="120" />
          <t-table-column data-index="pickUpSignName" title="提货签到" :width="120" />
          <t-table-column data-index="pickUpPictureName" title="提货图片" :width="120" />
          <t-table-column data-index="defaultPickUpRail" title="默认提货围栏" :width="120" />
          <t-table-column data-index="deliverySignName" title="送达签到" :width="120" />
          <t-table-column data-index="deliveryPictureName" title="送达图片" :width="120" />
          <t-table-column data-index="defaultDeliveryRail" title="默认送达围栏" :width="120" />
          <t-table-column data-index="returnOrderFlagName" title="正本回单" :width="120" />
          <t-table-column data-index="returnOrderPictureName" title="回单图片" :width="120" />
          <t-table-column data-index="returnOrderDeadline" title="回单期限" :width="120" />
          <t-table-column v-for="item in mextendedField_list" :key="item.fieldName" :data-index="item.fieldName" :title="item.displayName" :width="120" />
          <t-table-column data-index="createperson" title="创建人" :width="120" />
          <t-table-column data-index="createtime" title="创建时间" :width="120" />
          <t-table-column data-index="updateperson" title="修改人" :width="120" />
          <t-table-column data-index="updatetime" title="修改时间" :width="120" />
          <t-table-column key="action" title="操作" :width="180" fixed="right">
            <template slot-scope="text, record">
              <a-space>
                <a @click.stop="onEdit(record, 'view')" v-action:view>查看</a>
                <a @click.stop="onEdit(record, 'copy')" v-action:copy>复制</a>
                <a @click.stop="onEdit(record, 'edit')" v-action:edit>修改</a>
                <p-switch @change="toEnOrDis(record)" :checked="record.status === 10 ? true : false" size="small" v-action:status />
                <a @click.stop="toDel(record)" v-action:del>删除</a>
              </a-space>
            </template>
          </t-table-column>
        </t-table>
      </p-card>
      <p-card title="收货方信息">
        <a-space slot="extra">
          <p-button type="primary" @click="onEdit({}, 'consigneeAdd')" :disabled="!selectedData.id" v-action:child_add>新增</p-button>
          <p-button type="primary" @click="onConsigneeEnOrDis(10)" :disabled="!consigneeSelectedRowKeys.length" v-action:child_status>启用</p-button>
          <p-button type="danger" @click="onConsigneeEnOrDis(0)" :disabled="!consigneeSelectedRowKeys.length" v-action:child_status>停用</p-button>
          <p-button type="danger" @click="onConsigneeDel" :disabled="!consigneeSelectedRowKeys.length" v-action:child_del>删除</p-button>
          <p-button type="primary" @click="onConsigneeAddressAnalysis" :disabled="!consigneeSelectedRowKeys.length" v-action:child_mapParse>地址解析</p-button>
          <import-Button :importUrl="consigneeImportUrl" :tmpUrl="consigneeDownUrl" fileName="收货方模板" />
        </a-space>
        <t-table
          ref="consigneeTable"
          :extendedObjectCode="'5'"
          rowSelectFixed
          :id="$route.meta.menuId + '_consigneeTable'"
          dragle
          bordered
          row-key="id"
          :vScrollX="{enabled:false}"
          :vScrollY="{enabled:true,rows:5}"
          :data-source="consigneeDataSource"
          :remote-url="consigneeListRemoteUrl"
          :remoteData="consigneeListParams"
          :rowSelectType="2"
          @selectChange="selectChangeConsignee"
          :autoLoad="false"
          :pagination="false"
        >
          <t-table-column data-index="code" title="收货方编码" :width="120" />
          <t-table-column data-index="name" title="收货方名称" :width="120" />
          <t-table-column data-index="shortName" title="收货方简称" :width="120" />
          <t-table-column data-index="statusName" title="状态" :width="120" />
          <t-table-column data-index="contact" title="联系人" :width="120" />
          <t-table-column data-index="phoneNumber" title="手机号" :width="120" />
          <t-table-column data-index="landlineNumber" title="座机号" :width="120" />
          <t-table-column data-index="memo" title="备注" :width="120" />
          <t-table-column data-index="deliveryPatternName" title="配送方式" :width="120" />
          <t-table-column data-index="carrierTypeName" title="默认承运方类型" :width="120" />
          <t-table-column data-index="carrierName" title="默认承运方名称" :width="120" />
          <t-table-column data-index="vehiclePlateNumber" title="默认车辆" :width="120" />
          <t-table-column data-index="provinceName" title="省" :width="120" />
          <t-table-column data-index="cityName" title="市" :width="120" />
          <t-table-column data-index="districtName" title="区" :width="120" />
          <t-table-column data-index="address" title="详细地址" :width="120" />
          <t-table-column data-index="stationCode" title="站点编码" :width="120" />
          <t-table-column data-index="stationName" title="站点名称" :width="120" />
          <t-table-column data-index="stationDeliveryOrder" title="配送顺序" :width="120" />
          <t-table-column data-index="stationAreas" title="区域" :width="120" />
          <t-table-column data-index="longitude" title="经度" :width="120" />
          <t-table-column data-index="latitude" title="纬度" :width="120" />
          <t-table-column v-for="item in consigneeMextendedField_list" :key="item.fieldName" :data-index="item.fieldName" :title="item.displayName" :width="120" />
          <t-table-column key="action" title="操作" :width="180" fixed="right">
            <template slot-scope="text, record">
              <a-space>
                <a @click.stop="onEdit(record, 'consigneeView')" v-action:child_view>查看</a>
                <a @click.stop="onEdit(record, 'consigneeCopy')" v-action:child_copy>复制</a>
                <a @click.stop="onEdit(record, 'consigneeEdit')" v-action:child_edit>修改</a>
                <p-switch @change="toConsigneeEnOrDis(record)" :checked="record.status === 10 ? true : false" size="small" v-action:child_status />
                <a @click.stop="toConsigneeDel(record)" v-action:child_del>删除</a>
              </a-space>
            </template>
          </t-table-column>
        </t-table>
      </p-card>
    </p-spin>

    <!-- 编辑 -->
    <edit
      ref="edit"
      v-if="warehouse.includes(editType)"
      v-show="!addressAnalysisShow"
      :type="editType"
      :editId="editId"
      :options="options"
      :mextendedField_list="mextendedField_list"
      @back="editType = ''"
      @upadteAddress="upadteAddress"
    ></edit>

    <!-- 收货方 -->
    <consigneeEdit
      ref="consigneeEdit"
      v-if="consignee.includes(editType)"
      v-show="!addressAnalysisShow"
      :type="editType"
      :editId="editId"
      :customerData="selectedData"
      :options="options"
      :mextendedField_list="consigneeMextendedField_list"
      @back="consigneeBack"
      @consigneeUpadteAddress="consigneeUpadteAddress"
    ></consigneeEdit>

    <!-- 地址解析 -->
    <addressAnalysis :showType="addressAnalysisShow" :type="addressType" :searchParams="addressSearchData" :addressData="addressData" @back="addressBack" @returnData="onMapReturnData" />
  </div>
</template>

<script>
import addressAnalysis from '@/blocks/addressAnalysis/index.addressAnalysis.vue'; // 地址解析
import importButton from '@/blocks/components/importButton/index.importButton.vue';
import { initDictionary, extendedFieldList } from '@/blocks/utils';

import edit from './modules/edit';
import consigneeEdit from './modules/consigneeEdit';
import {
  listRemoteUrl,
  consigneeListRemoteUrl,
  activeCustomer,
  deleteCustomer,
  neverDelete,
  activeCustomerReceiver,
  deleteCustomerReceiver,
  neverDeleteCustomerReceiver,
  importUrl,
  downUrl,
  consigneeImportUrl,
  consigneeDownUrl,
} from './js/api';

export default {
  components: { edit, consigneeEdit, addressAnalysis, importButton },
  data() {
    return {
      spinning: false,
      // 空-列表页 view-查看 add-新增 edit-修改 copy-复制 address-地址解析 consigneeView-收货方查看 consigneeAdd-收货方新增 consigneeEdit-收货方修改 consigneeCopy-收货方复制
      addressType: 'customer',
      editType: '',
      editId: '',
      warehouse: ['view', 'add', 'edit', 'copy'],
      consignee: ['consigneeView', 'consigneeAdd', 'consigneeEdit', 'consigneeCopy'],
      importUrl,
      downUrl,
      consigneeImportUrl,
      consigneeDownUrl,

      form: {
        customerCode: '',
        customerName: '',
        cargoOwnerName: '',
      },
      options: {
        MAINDATA_STATUS: [],
        COOPERATIVE_NATURE: [],
        BANK: [],
        ENABLE_STATUS: [],
        LINE_CARRIER_TYPE: [],
      },

      // 主表格
      dataSource: [],
      selectedRowKeys: [],
      listRemoteUrl,
      listParams: {},
      selectedData: {},
      activeID: '',

      // 收货方表格
      consigneeDataSource: [],
      consigneeSelectedRowKeys: [],
      consigneeListRemoteUrl,
      consigneeListParams: {},

      mextendedField_list: [],
      consigneeMextendedField_list: [],

      addressAnalysisShow: 0,
      addressData: {},
      addressSearchData: {},
    };
  },
  mounted() {
    initDictionary([
      { objectcode: 'SIGN_TIME_UNIT' },
      { objectcode: 'PICK_UP_SIGN_TIME' },
      { objectcode: 'MAINDATA_STATUS' },
      { objectcode: 'DELIVERY_METHOD_TYPE' },
      { objectcode: 'COOPERATIVE_NATURE' },
      { objectcode: 'BANK' },
      { objectcode: 'ENABLE_STATUS' },
      { objectcode: 'LINE_CARRIER_TYPE' },
    ]).then((res) => {
      for (let key in res) {
        res[key].forEach((item) => {
          item.value = +item.value;
        });
      }
      this.options = { ...this.options, ...res };
    });
    extendedFieldList({ extendedObjectCode: '4' }).then((res) => (this.mextendedField_list = res));
    extendedFieldList({ extendedObjectCode: '5' }).then((res) => (this.consigneeMextendedField_list = res));
  },
  methods: {
    selectChange(selectKey,selectData) {
      this.selectedRowKeys = selectKey
    },
    selectChangeConsignee(selectKey,selectData) {
      this.consigneeSelectedRowKeys=selectKey
    },
    // 查询
    onSearch() {
      this.listParams = { ...this.form };
    },
    // 重置
    onReset() {
      this.form = {
        customerCode: '',
        customerName: '',
        cargoOwnerName: '',
      };
    },

    // 新增、修改、复制、查看
    onEdit(record = { id: '' }, type) {
      this.editId = record.id;
      this.editType = type;
    },

    // 启用、停用
    onEnOrDis(status) {
      this.WhetherToEnable(status === 10 ? activeCustomer : deleteCustomer, this.selectedRowKeys, status === 10 ? '是否启用?' : '停用客户，客户的收货方同时停用，请确认是否停用客户！');
    },
    toEnOrDis(record) {
      this.WhetherToEnable(record.status === 10 ? deleteCustomer : activeCustomer, [record.id], record.status === 10 ? '停用客户，客户的收货方同时停用，请确认是否停用客户！' : '是否启用?');
    },
    // 删除
    onDel() {
      let list = this.selectedRowKeys.map((item) => {
        return { id: item };
      });
      this.WhetherToEnable(neverDelete, list, '是否删除?');
    },
    toDel(record) {
      this.WhetherToEnable(neverDelete, [{ id: record.id }], '是否删除?');
    },
    WhetherToEnable(method, idList, text) {
      let self = this;
      this.$confirm({
        title: text,
        onOk() {
          return new Promise((resolve, reject) => {
            method(idList)
              .then((res) => {
                if (res.success) {
                  self.$message.success(res.message);
                  self.onSearch();
                } else {
                  self.$exception(res);
                }
                resolve();
              })
              .catch((res) => {
                self.$exception(res);
                resolve();
              });
          });
        },
      });
    },

    // 地址解析
    onAddressAnalysis() {
      this.addressType = 'customer';
      this.addressData = {};
      this.addressSearchData = { ids: [...this.selectedRowKeys] };
      this.addressAnalysisShow = 2;
    },
    onConsigneeAddressAnalysis() {
      this.addressType = 'consignee';
      this.addressData = {};
      this.addressSearchData = { ids: [...this.consigneeSelectedRowKeys], customerId: this.selectedData.id };
      this.addressAnalysisShow = 2;
    },
    addressBack() {
      this.addressAnalysisShow = 0;
      this.consigneeDataSource = [];
      if (!this.editType) {
        if (this.addressType === 'customer') {
          this.$refs.masterTable.reload();
        } else {
          this.$refs.consigneeTable.reload();
        }
      }
    },
    upadteAddress(addressData) {
      this.addressType = 'customer';
      this.addressData = addressData;
      this.addressAnalysisShow = 1;
    },
    consigneeUpadteAddress(addressData) {
      this.addressType = 'consignee';
      this.addressData = addressData;
      this.addressAnalysisShow = 1;
    },
    onMapReturnData(value) {
      if (this.addressType === 'customer') {
        this.$set(this.$refs.edit.form, 'address', value.address);
        this.$set(this.$refs.edit.form, 'longitude', value.longitude);
        this.$set(this.$refs.edit.form, 'latitude', value.latitude);
      } else {
        this.$set(this.$refs.consigneeEdit.form, 'address', value.address);
        this.$set(this.$refs.consigneeEdit.form, 'longitude', value.longitude);
        this.$set(this.$refs.consigneeEdit.form, 'latitude', value.latitude);
      }

      this.addressAnalysisShow = 0;
    },

    // 行点击
    masterClickRow(event, activeID, rowRecord) {
      this.selectedData = rowRecord;
      this.consigneeListParams = { customerId: rowRecord.id };
    },

    // 车站启用、停用
    onConsigneeEnOrDis(status) {
      this.PackingWhetherToEnable(status === 10 ? activeCustomerReceiver : deleteCustomerReceiver, this.consigneeSelectedRowKeys, status === 10 ? '启用' : '停用');
    },
    toConsigneeEnOrDis(record) {
      this.PackingWhetherToEnable(record.status === 10 ? deleteCustomerReceiver : activeCustomerReceiver, [record.id], record.status === 10 ? '停用' : '启用');
    },
    // 车站删除
    onConsigneeDel() {
      let list = this.consigneeSelectedRowKeys.map((item) => {
        return { id: item };
      });
      this.PackingWhetherToEnable(neverDeleteCustomerReceiver, list, '删除');
    },
    toConsigneeDel(record) {
      this.PackingWhetherToEnable(neverDeleteCustomerReceiver, [{ id: record.id }], '删除');
    },
    PackingWhetherToEnable(method, idList, text) {
      let self = this;
      this.$confirm({
        title: '是否' + text + '?',
        onOk() {
          return new Promise((resolve, reject) => {
            method(idList)
              .then((res) => {
                if (res.success) {
                  self.$message.success(res.message);
                  self.$refs.consigneeTable.reload();
                } else {
                  self.$exception(res);
                }
                resolve();
              })
              .catch((res) => {
                self.$exception(res);
                resolve();
              });
          });
        },
      });
    },

    consigneeBack(rowRecord) {
      this.editType = '';
      this.$nextTick(() => {
        this.masterClickRow('', '', rowRecord);
        this.activeID = rowRecord.id;
      });
    },
  },
};
</script>