<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch && !!!customerId" label-width="68px">
      <el-form-item :label="$t('客户名称')" prop="customerId">
       <customer-select v-model="queryParams.customerId" ></customer-select>
      </el-form-item>
      <el-form-item :label="$t('投诉类型')" prop="type">
        <el-select v-model="queryParams.type" :placeholder="$t('请选择投诉类型')" clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.CUSTOMER_COMPLAINT_TYPE)"
                       :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('订单号')" prop="orderId">
        <el-input v-model="queryParams.orderId" :placeholder="$t('请输入订单号')" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item :label="$t('提单号')" prop="ladingbillId">
        <el-input v-model="queryParams.ladingbillId" :placeholder="$t('请输入提单号')" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item :label="$t('处理状态')" prop="status">
        <el-select v-model="queryParams.status" :placeholder="$t('请选择处理状态')" clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.CUSTOMER_COMPLAINT_STATUS)"
                       :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('投诉编号')" prop="code">
        <el-input v-model="queryParams.code" :placeholder="$t('请输入投诉编号')" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item :label="$t('创建时间')">
        <el-date-picker v-model="dateRangeCreateTime" style="width: 240px" value-format="yyyy-MM-dd"
                        type="daterange" 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>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" v-show="!!!customerId" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['ecw:customer-complaint: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="['ecw:customer-complaint:export']">{{$t('导出')}}</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">
      <el-table-column :label="$t('投诉编号')" align="center" prop="code" >
      </el-table-column>
      <el-table-column :label="$t('投诉类型')" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.CUSTOMER_COMPLAINT_TYPE" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('客户名称')" align="center" >
        <template slot-scope="scope">
          <div>{{ formatCustomerName(scope.row.customerId) }}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('投诉日期')" align="center"  width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime)}}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('登记客服')" align="center" prop="adminNickname">
      </el-table-column>
      <el-table-column :label="$t('状态')" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.CUSTOMER_COMPLAINT_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('提单号')" align="center" prop="ladingbillId" />
      <el-table-column :label="$t('订单号')" align="center" prop="orderId" />
      <el-table-column :label="$t('处理时间')" align="center" prop="handleAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.handleAt)}}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('赔付金额')" align="center" prop="handleAt" width="180">
        <template slot-scope="scope">
          {{ scope.row.status === 3 ?  scope.row.indemnity  : '/'}}
          <span v-if="scope.row.status === 3">{{getCurrencyLabel(scope.row.currencyUnit)}}</span>
        </template>
      </el-table-column>
      <el-table-column :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="['ecw:customer-complaint:update']">{{$t('修改')}}</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleHandle(scope.row)"
                     v-hasPermi="['ecw:customer-complaint:update']" v-show="scope.row.status != 3">{{$t('处理')}}</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['ecw:customer-complaint:delete']">{{$t('删除')}}</el-button>
           <el-button size="mini" type="text" icon="el-icon-edit" @click="handleSee(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"/>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <div class="formShow">
          <div>
          <el-form-item :label="$t('客户名称')" prop="customerId">
            <customer-select v-model="form.customerId" ></customer-select>
          </el-form-item>
          <el-form-item :label="$t('投诉类型')" prop="type">
            <el-select v-model="form.type" :placeholder="$t('请选择投诉类型')">
              <el-option v-for="dict in getDictDatas(DICT_TYPE.CUSTOMER_COMPLAINT_TYPE)"
                         :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('订单号')" prop="orderId">
            <el-select
              v-model="form.orderId"
              filterable
              remote
              :placeholder="$t('请输入订单号')"
              :remote-method="getOrderList"
              :loading="loading">
              <el-option
                v-for="item in orderList"
                :key="item.value"
                :label="item.value"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('提单号')" prop="ladingbillId">
            <el-select
              v-model="form.ladingbillId"
              filterable
              remote
              :placeholder="$t('请输入提单号')"
              :remote-method="getBillList"
              :loading="loading">
              <el-option
                v-for="item in billList"
                :key="item.value"
                :label="item.value"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          </div>
          <div v-if="form.id">
            <el-form-item :label="$t('投诉时间')">
                <span>{{parseTime(form.createTime)}}</span>
            </el-form-item>
            <el-form-item :label="$t('投诉状态')">
              <dict-selector :type="DICT_TYPE.CUSTOMER_COMPLAINT_STATUS" :disabled="true" form-type="radio" v-model="form.status" :filter="(e) => e.value == '1' ||e.value == '2' || e.value == '3'"
                             :formatter="Number"></dict-selector>
            </el-form-item>
          </div>
        </div>
        <el-form-item :label="$t('投诉内容')" prop="content">
          <el-input v-model="form.content" type="textarea" :placeholder="$t('请输入内容')" />
        </el-form-item>
        <el-form-item v-show="form.status == '2'||form.status == '3'" :label="$t('查明原因')" required>
          <el-input type="textarea" :placeholder="$t('请输入查明原因')" v-model="form.ascertainReason"></el-input>
        </el-form-item>
        <el-form-item v-show="form.status == '2'||form.status == '3'" :label="$t('处理方案')">
          <el-input v-model="form.plan" :placeholder="$t('请输入处理方案')"></el-input>
        </el-form-item>

        <el-form-item v-show="form.status == '3'" :label="$t('处理结果')" required>
          <el-input type="textarea" :placeholder="$t('请输入处理结果')" v-model="form.result"></el-input>
        </el-form-item>
       <el-form-item v-show="form.status == '3'" :label="$t('赔付金额')">
         <el-input v-model="form.indemnity" :placeholder="$t('请输入赔付金额')">
            <el-select slot="append" defaultable v-model="form.currencyUnit" :placeholder="$t('请选择货币单位')" style="width: 110px">
              <el-option v-for="item in currencyList" :key="item.id" :label="item.titleZh" :value="item.id" />
            </el-select>
         </el-input>
       </el-form-item>
        <el-form-item v-show="form.status == '3'" :label="$t('处理时间')" required>
          <span>{{parseTime(form.handleAt)}}</span>
        </el-form-item>
 <!--       <el-form-item label="处理状态" prop="status" v-if="form.id">
          <span v-if="!form.id">{{ getDictDataLabel(DICT_TYPE.CUSTOMER_COMPLAINT_STATUS, 1) }}</span>
          <el-select v-else v-model="form.status" placeholder="请选择处理状态">
            <el-option v-for="dict in getDictDatas(DICT_TYPE.CUSTOMER_COMPLAINT_STATUS)"
                       :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
          </el-select>
        </el-form-item> -->
      </el-form>

      <!-- <customer-follow v-if="!!this.form.id" :id="form.id" :customer-id="form.customerId"></customer-follow> -->

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{$t('确 定')}}</el-button>
        <el-button @click="cancel">{{$t('取 消')}}</el-button>
      </div>
    </el-dialog>


    <el-dialog :title="title" :visible.sync="openCustomer" width="900px" append-to-body>
      <el-form ref="form" :inline="true" :model="form" label-width="80px">
          <el-form-item :label="$t('客户名称')+':'">
            <div>{{ formatCustomerName(form.customerId) }}</div>
          </el-form-item>
          <el-form-item :label="$t('投诉类型') +':'">
              <dict-tag :type="DICT_TYPE.CUSTOMER_COMPLAINT_TYPE" :value="form.type" />
          </el-form-item>
          <el-form-item :label="$t('订单号')+':'" prop="orderId" >
            <div>{{form.orderId}}</div>
          </el-form-item>
          <el-form-item label="提单号:" prop="ladingbillId" >
            <div>{{form.ladingbillId|| $t('无')}}</div>
          </el-form-item>
          <div>
            <el-form-item :label="$t('投诉时间')+':'">
                <span>{{parseTime(form.createTime)}}</span>
            </el-form-item>
            <el-form-item :label="$t('投诉状态')+':'">
               <dict-tag :type="DICT_TYPE.CUSTOMER_COMPLAINT_STATUS" :value="form.status" />
            </el-form-item>
          </div>
        <el-form-item  :label="$t('投诉内容')+':'" >
          <div>{{form.content|| $t('无')}}</div>
          </el-form-item>
        <el-form-item v-show="form.status == '2'||form.status == '3'" :label="$t('查明原因')+':'" prop="ascertainReason" >
          <div>{{form.ascertainReason||'无'}}</div>
          </el-form-item>
        <el-form-item v-show="form.status == '2'||form.status == '3'" :label="$t('处理方案')+':'" prop="plan" >
          <div>{{form.plan||$t('无')}}</div>
          </el-form-item>
        <el-form-item v-show="form.status == '3'" :label="$t('处理结果')+':'" prop="result" >
        <div>{{form.result||$t('无')}}</div>
        </el-form-item>
        <el-form-item v-show="form.status == '3'" :label="$t('赔付金额')+':'">
          <span>{{form.indemnity||0}}</span>
          <span>{{getCurrencyLabel(form.currencyUnit)}}</span>
        </el-form-item>
        <el-form-item v-show="form.status == '3'" :label="$t('处理时间')+':'">
          <span>{{parseTime(form.handleAt)}}</span>
        </el-form-item>
      </el-form>
      <customer-follow v-if="!!this.form.id" :id="form.id" :customer-id="form.customerId"></customer-follow>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="openCustomer=false">{{$t('确 定')}}</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="$t('提示')"
      :visible.sync="handle.dialogVisible"
      width="30%"
    >
      <el-form ref="form" :model="form" label-width="80px"  :rules="rules">
        <el-form-item :label="$t('投诉类型')">
          <dict-selector :type="DICT_TYPE.CUSTOMER_COMPLAINT_STATUS" form-type="radio" v-model="form.status"
                         :filter="(e) => e.value == '2' || e.value == '3'" :formatter="Number"></dict-selector>
        </el-form-item>
        <el-form-item v-show="form.status == '2'" :label="$t('查明原因')" required >
          <el-input type="textarea" :placeholder="$t('请输入查明原因')" v-model="form.ascertainReason"></el-input>
        </el-form-item>
        <el-form-item v-show="form.status == '2'" :label="$t('处理方案')">
          <el-input v-model="form.plan" :placeholder="$t('请输入处理方案')"></el-input>
        </el-form-item>

        <el-form-item v-show="form.status == '3'" :label="$t('处理结果')" required>
          <el-input type="textarea" :placeholder="$t('请输入处理结果')" v-model="form.result"></el-input>
        </el-form-item>
        <el-form-item v-show="form.status == '3'" :label="$t('赔付金额')">
          <el-input v-model="form.indemnity" :placeholder="$t('请输入赔付金额')">
            <el-select slot="append" defaultable v-model="form.currencyUnit" :placeholder="$t('请选择货币单位')" style="width: 110px">
              <el-option v-for="item in currencyList" :key="item.id" :label="item.titleZh" :value="item.id" />
            </el-select>
          </el-input>
        </el-form-item>
        <el-form-item v-show="form.status == '3'" :label="$t('处理时间')" required>
          <el-date-picker type="datetime" v-model="form.handleAt" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handle.dialogVisible = false">{{$t('取 消')}}</el-button>
        <el-button type="primary" @click="submitForm">{{$t('确 定')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { createCustomerComplaint, updateCustomerComplaint, deleteCustomerComplaint, getCustomerComplaint, getCustomerComplaintPage, exportCustomerComplaintExcel } from "@/api/ecw/customerComplaint";
import {getCustomerList, getCustomerSelect} from '@/api/ecw/customer'
import CustomerFollow from "../../../components/CustomerFollow"
import DictSelector from '@/components/DictSelector'
import { DICT_TYPE, getDictDataLabel, getDictDatas } from '@/utils/dict'
import { getBillNoSearch, getOrderNoSearch } from '@/api/ecw/order'
import customerSelect from '@/views/ecw/customer/customerSelect'
import { getCurrencyPage } from "@/api/ecw/currency";

export default {
  name: "CustomerComplaint",
  /**
   * 可以单独作为页面，也可以作为组件被被客户详情页调用。
   * 作为组件时要传入 customerId，用于限制范围和隐藏搜索筛选
   */
  props: {
    customerId: Number
  },
  components: {
    CustomerFollow,
    DictSelector,
    customerSelect
  },
  data() {
    return {
      DICT_TYPE,
      getDictDatas,
      getDictDataLabel,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户投诉列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openCustomer:false,
      dateRangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        customerId: this.customerId,
        type: null,
        orderId: null,
        ladingbillId: null,
        status: null,
        adminId: null,
        code: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        customerId: [{ required: true, message: this.$t('客户名称不能为空'), trigger: "change" }],
        type: [{ required: true, message: this.$t('投诉类型不能为空'), trigger: "change" }],
        content: [{ required: true, message: this.$t('投诉内容不能为空'), trigger: "blur" }],
      },

      myFollowCustomerList: [],

      customerSelect: [],

      // 处理
      handle: {
        dialogVisible: false
      },

      billList: [],
      orderList: [],
      params: {
        page: 1,
        rows: 20,
      },
      currencyList:[]
    };
  },
  created() {
    this.getList();
     getCurrencyPage(this.params).then(res => this.currencyList = res.data.list)

  },
  methods: {

    getBillList(key){
      getBillNoSearch({key, pageNo: 1, pageSize: 20}).then(r => {
        if (r.code === 0){
          this.billList = r.data.list
        }
      })
    },
    getCurrencyLabel(id){
      var label = this.currencyList.filter(item=>item.id == id)
      if(label.length>0) return label[0].titleZh
      return ''
    },
    getOrderList(key){
      getOrderNoSearch({key, pageNo: 1, pageSize: 20}).then(r => {
        if (r.code === 0){
          this.orderList = r.data.list
        }
      })
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 处理查询参数
      let params = {...this.queryParams};
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      // 执行查询
      getCustomerComplaintPage(params).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
        getCustomerList({ids:this.list.map(i => i.customerId).join(',')}).then(r => {
          this.customerSelect = r.data
        })
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        customerId: this.customerId,
        type: undefined,
        orderId: undefined,
        ladingbillId: undefined,
        content: undefined,
        status: undefined,
        ascertainReason: undefined,
        plan: undefined,
        result: undefined,
        indemnity: undefined,
        currencyUnit: undefined,
        handleAt: undefined,
        cancelReason: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = this.$t('添加客户投诉');
      // 新增客诉默认状态为待处理
      this.form.status = 1;
    },

    /** 查看按钮操作 */
    handleSee(row) {
      this.reset();
      const id = row.id;
      getCustomerComplaint(id).then(response => {
        this.form = response.data;
        this.openCustomer = true;
        this.title = this.$t('投诉详情');
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getCustomerComplaint(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = this.$t('修改客户投诉');
      });
    },
    handleHandle(row){
      this.reset();
      const id = row.id;
      getCustomerComplaint(id).then(response => {
        this.form = response.data;
        this.handle.dialogVisible = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }

        // 修改的提交
        if (this.form.id != null) {
          if(this.form.status==2){
            if(!this.form.ascertainReason){
              this.$modal.msgError(this.$t('请输入查明原因'));
              return
            }
          }
          if(this.form.status==3){
            if(!this.form.result){
              this.$modal.msgError(this.$t('请输入处理结果'));
              return
            }
            if(!this.form.handleAt){
              this.$modal.msgError(this.$t('请输入处理时间'));
              return
            }
          }
          updateCustomerComplaint(this.form).then(response => {
            this.$modal.msgSuccess(this.$t('修改成功'));
            this.open = false;
            this.handle.dialogVisible = false
            this.getList();
          });
          return;
        }
        // 添加的提交
        createCustomerComplaint(this.form).then(response => {
          this.$modal.msgSuccess(this.$t('新增成功'));
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm(this.$t('是否确认删除客户投诉编号为"') + id + this.$t('"的数据项?')).then(function() {
          return deleteCustomerComplaint(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t('删除成功'));
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      // 执行导出
      this.$modal.confirm(this.$t('是否确认导出所有客户投诉数据项?')).then(() => {
          this.exportLoading = true;
          return exportCustomerComplaintExcel(params);
        }).then(response => {
          this.$download.excel(response, '客户投诉列表.xls');
          this.exportLoading = false;
        }).catch(() => {});
    },
    /** 格式化邮件账号 */
    formatCustomerName(customerId) {
      for (const customer of this.customerSelect) {
        if (customer.id === customerId) {
          return customer.name;
        }
      }
      return this.$t('找不到客户') + ':' + customerId;
    }
  }
};
</script>
<style scoped>
  .formShow{
    display: flex;
  }
  .formShow div{
    flex: 1;
  }
</style>
