<template>
  <a-modal
    :title="title"
    :width="width"
    v-model:open="modalVisible"
    centered
    :closable="true"
    :keyboard="false"
    :maskClosable="false"
  >
    <template #footer>
      <a-popconfirm
        title="您确定要删除这个询盘吗"
        ok-text="是"
        cancel-text="否"
        @confirm="handleDel"
        v-if="showDelBtn"
      >
        <a-button>删除</a-button>
      </a-popconfirm>
      <a-button type="primary" @click="handleCancel">关闭</a-button>
    </template>

    <div class="wrap">
      <a-spin :spinning="spinning" tip="正在修改询盘分类">
        <p><span>咨询时间：</span>{{ filter_Null_format(record.recordCtime) }}</p>
        <p><span>公司：</span>{{ filter_Null_format(record.formCompany) }}</p>
        <p><span>姓名：</span>{{ filter_Null_format(record.contact)}}</p>
        <p><span>邮箱：</span><a :href="'mailto:'+record.fromEmail">{{filter_Null_format(record.fromEmail)}}</a></p>
        <p><span>电话：</span>{{ filter_Null_format(record.phone)}}</p>
        <p><span>WhatsApp：</span>{{filter_Null_format(record.whatsApp)}}</p>
        <p><span>客户IP：</span>{{ filter_Null_format(record.customerIp) }}</p>
        <p style="display: none"><span>来源IP：</span>{{ filter_Null_format(record.fromIp) }}</p>
        <p><span>来源国家/地区：</span>{{ filter_Null_format(record.countryName) }}</p>
        <template v-if="record.cartItems != null">
          <p><span>感兴趣的产品：</span>
            <div class="product-list">
              <template v-for="item in record.cartItems">
                数量：{{ item.quantity }}, 产品： <a :href="item.productLink" target="_blank">{{ item.productTitle }}</a><br/>
              </template>
            </div>
          </p>
        </template>

        <p><span>来源页：</span>
          <template v-if="!record.fromPage">-</template>
          <template v-else-if="record.fromPage.indexOf('http') < 0">-</template>
          <template v-else-if="record.fromPage.indexOf('http') === 0">
            <template v-if="record.fromPage.lastIndexOf('/') <= 7">
              <a
v-if="edition === 1" :href="record.fromPage" target="_blank"
                 style="text-decoration: underline">Home</a>
              <span v-else>Home</span>
            </template>
            <template v-else>
              <a
v-if="edition === 1" :href="record.fromPage" target="_blank"
                 style="text-decoration: underline">{{ record.fromPage.substring(record.fromPage.lastIndexOf('/') + 1) }}</a>
              <span v-else>{{ record.fromPage.substring(record.fromPage.lastIndexOf('/') + 1) }}</span>
            </template>
          </template>
          <template v-else-if="record.fromPage.indexOf('http') > 0">
            <a
v-if="edition === 1" :href="record.fromPage.substring(record.fromPage.indexOf('http'))" target="_blank"
               style="text-decoration: underline">{{ record.fromPage.substring(0, record.fromPage.indexOf('http')) }}</a>
            <span v-else>{{ record.fromPage.substring(0, record.fromPage.indexOf('http')) }}</span>
          </template>
          <template v-else>-</template>
        </p>
        <p v-if="userEffectiveOption != undefined"><span>询盘分类：</span>
          <a-radio-group v-model:value="modelUserEffective" @change="onChangeUserEffect">
            <a-radio v-for="item in userEffectiveOption" :key="item.value" :value="parseInt(item.value)" >
              {{item.label}}
            </a-radio>
          </a-radio-group>
        </p>
        <p class="translate">
          <span>详细内容：</span>
          <a-spin tips="翻译中" :spinning="translateStatus">
            <span style="flex: auto;" >
              <div v-html="record.context" v-if="translateContent == ''">
              </div>
              <div v-html="translateContent">
              </div>
                  <!-- {{translateContent == '' ?  record.context : translateContent}} -->
                  <i @click="enquiryTransContent">
                   <img v-if="translateContent == '' " src="../../.././../assets/enquiry/translate1.svg" />
                  </i>
                  <i @click="backToEcglish">
                   <img v-if="translateContent != '' " src="../../.././../assets/enquiry/translate2.svg" />
                  </i>
               </span>
          </a-spin>
        </p>
        <p v-if="record.userEffective == 0 && (userRole.indexOf('admin') > -1 || userRole.indexOf('adweb_admin') > -1 || userRole.indexOf('adweb_seo_manager') > -1 || userRole.indexOf('adweb_site_manager') > -1)"><span>疑似原因：</span>{{  filter_Null_format(record.effectiveReason) }}</p>
        <div class="info" v-if="record.specialFieldList && record.specialFieldList.length > 0">
          <a-descriptions title="扩展信息" bordered :column=1  class="slef_desc">
            <a-descriptions-item :label="item.field" v-for="item in record.specialFieldList">
              {{  filter_Null_format(item.value) }}
            </a-descriptions-item>
          </a-descriptions>
        </div>
      </a-spin>
    </div>

    <!-- 垃圾询盘原因填写   -->
    <a-modal
      :title="wasteEnquiryTitle"
      :width="width"
      v-model:open="wasteEnquiryVisible"
      centered
      :closable="true"
      :keyboard="false"
      :maskClosable="false"
      @cancel="wasteEnquiryCancel"
    >
      <template #footer>
        <a-button @click="wasteEnquiryCancel">关闭</a-button>
        <a-button type="primary" @click="wasteEnquiryOk">确认</a-button>
      </template>

      <div class="wrap">
        <div class="ant-alert ant-alert-info" style="color: #e74c3c;padding: 5px 8px;">
          <span>&nbsp&nbsp&nbsp&nbsp当垃圾询盘类型选择确认后，对应类型的内容便会加入对应黑名单中，同时获取询盘时会把此内容的询盘当作垃圾询盘处理，请谨慎操作。</span>
        </div>
        <p><span>垃圾询盘类型：</span>
          <a-radio-group v-model:value="wasteEnquiryType" @change="onChangeWasteEnquiry">
            <a-radio v-for="item in wasteEnquiryOption" :key="item.value" :value="item.value" >
              {{item.label}}
            </a-radio>
          </a-radio-group>
        </p>
        <p v-if="wasteEnquiryType === 'keyword'">
          <span>关键词：</span>
          <span style="flex: auto">
            详细内容：{{record.context}}
             <i>
               <a-textarea v-model:value="wasteEnquirySeason" :placeholder="wasteEnquiryPlaceholder" :auto-size="{ minRows: 3 }" />
             </i>
          </span>
        </p>
        <p v-if="wasteEnquiryType === 'other'">
          <span>原因：</span>
          <a-textarea v-model:value="wasteEnquirySeason" :placeholder="wasteEnquiryPlaceholder" :auto-size="{ minRows: 3 }" />
        </p>
      </div>
    </a-modal>
  </a-modal>
</template>

<script lang="js">

  import {getAction, postActionForm} from '/@/api/manage/manage'

  import {useUserStore} from "@/store/modules/user";
  import {useMessage} from "@/hooks/web/useMessage";

  const { createMessage } = useMessage();

  export default {
    name: 'EnquiryDetail',

    props:{
      userEffectiveOption: Array,
      showDelBtn:{
        default: false,
        type: Boolean,
        //目前只支持询盘列表通过询盘详情删除询盘，其他地方不展示删除按钮
      }
    },
    data () {
      return {
        title:"询盘详情",
        width:900,
        modalVisible: false,
        record:{},
        spinning:false,
        value:1,
        translateStatus:false,
        translateContent:'',
        modelUserEffective:2,
        edition: 1,
        userRole: '',
        wasteEnquiryTitle:"垃圾询盘类型",
        wasteEnquiryVisible: false,
        wasteEnquiryOption:[{label:'关键词',value:'keyword'},{label:'邮箱',value:'email'},{label:'IP',value:'ip'},{label:'其他',value:'other'}],
        wasteEnquirySeason:'',
        wasteEnquiryType:'',
        wasteEnquiryPlaceholder:''
      }
    },

    mounted() {
      this.userRole = useUserStore().roleList;
    },

    methods: {
      init (record) {
        this.translateContent = ''
        this.modalVisible=true
        this.record = record
        this.modelUserEffective = record.userEffective

        record.cartItems = JSON.parse(record.cartItems);
      },

      filter_Null_format(value) {

        if(value === '' || value === null || value === undefined){
          return  '--'
        }else{
          return value
        }
      },

      handleCancel () {
        this.$emit('close');
        this.translateContent = ''
        this.modalVisible = false;
      },

      async handleDel() {
        //目前该方法只在询盘列表使用
        await getAction('/adweb/adwebEnquiry/delBatch', {id: this.record.id}).then((res) => {
          if (res.success) {
           createMessage.success(`删除询盘成功！`)
          } else {
            if (res.code == 403) {
             createMessage.warning(res.message)
            } else {
             createMessage.error('删除失败！')
            }
          }
        })
        //当删除之后，调用父组件中的重新刷新
        this.$emit('reload');
        this.modalVisible = false;
      },

      onChangeUserEffect(e){
        let that = this

        if(e.target.value === 0){
          that.wasteEnquiryVisible = true
        }else{
          that.submitUserEffect();
        }
      },

      //翻译
      enquiryTransContent(r) {
        let that = this;
        that.translateStatus = true;
        // 创建一个表单数据
        const formData = new FormData();
        formData.append('id', that.record.id);
        formData.append('query', that.translateContent === '' ?  that.record.context : that.translateContent);

        let recordId = that.record.id;
        postActionForm('/adweb/adwebEnquiry/enquiryTrans', formData, 1000 * 60 * 2).then(function(res) {
          that.translateStatus = false
          if (res.code === 200) {
            let beforeList = res.result;
            if(beforeList == null){
              createMessage.error("该内容暂不支持翻译")
              return;
            }
            if (beforeList.length > 0) {
              that.translateContent = beforeList
            }
          } else {
            createMessage.error("该内容暂不支持翻译")
          }
        }).catch(function(err) {
          console.log(err)
        })
      },

      backToEcglish(){
        this.translateContent = ''
      },

      wasteEnquiryOk(){
        let that = this;
        if(that.wasteEnquiryType === 'keyword'){
          let season = that.wasteEnquirySeason.trim();
          if(season == null || season === ""){
            createMessage.warning("关键词不能为空")
            that.wasteEnquirySeason = null;
            return;
          }
        }
        if(that.wasteEnquiryType === 'other'){
          let season = that.wasteEnquirySeason.trim();
          if(season == null || season === ""){
            createMessage.warning("原因不能为空")
            that.wasteEnquirySeason = null;
            return;
          }
        }
        that.wasteEnquiryVisible = false;
        that.submitUserEffect();
      },
      wasteEnquiryCancel(){
        let that = this;
        that.wasteEnquiryVisible = false;
        that.modelUserEffective = that.record.userEffective;
        that.wasteEnquiryType = "";
        that.wasteEnquirySeason = "";
        that.wasteEnquiryPlaceholder = "";
      },
      onChangeWasteEnquiry(e){
        let that = this;
        that.wasteEnquirySeason = "";
        that.wasteEnquiryType = e.target.value;
        if(that.wasteEnquiryType === 'email'){
          that.wasteEnquirySeason = that.record.fromEmail;
        }
        if(that.wasteEnquiryType === 'ip'){
          that.wasteEnquirySeason = that.record.customerIp;
        }
        if(that.wasteEnquiryType === 'keyword'){
          that.wasteEnquiryPlaceholder = "请输入关键词";
        }
        if(that.wasteEnquiryType === 'other'){
          that.wasteEnquiryPlaceholder = "请输入原因";
        }
      },

      submitUserEffect(){
        let that = this;
        this.spinning = true
        let d = {
          id: that.record.id,
          siteId: that.record.siteId,
          siteCode: that.record.siteCode,
          userEffective: that.modelUserEffective,
          wasteEnquiryType: that.wasteEnquiryType,
          wasteEnquirySeason: that.wasteEnquirySeason
        }
        postActionForm('/adweb/adwebEnquiry/update/user/effective', d).then(function(res) {
          that.spinning = false
          if (res.code === 200) {
            createMessage.success('分类修改成功！');
            that.$emit('ok')
            that.record.userEffective = that.modelUserEffective
            if(that.wasteEnquiryType === "ip"){
              that.record.effectiveReason = "人工操作-ip-" + that.wasteEnquirySeason
            }else if(that.wasteEnquiryType === "email"){
              that.record.effectiveReason = "人工操作-邮箱-" + that.wasteEnquirySeason
            }else if(that.wasteEnquiryType === "keyword"){
              that.record.effectiveReason = "人工操作-关键词-" + that.wasteEnquirySeason
            }else if(that.wasteEnquiryType === "other"){
              that.record.effectiveReason = "人工操作-其他-" + that.wasteEnquirySeason
            }

          } else {
            if (res.code === 403) {
              createMessage.warning(res.message)
            } else {
              createMessage.error('分类修改失败！')
            }
          }
        }).catch(function(err) {
          console.log(err)
        }).finally(()=>{
          that.wasteEnquiryType = "";
          that.wasteEnquirySeason = "";
          that.wasteEnquiryPlaceholder = "";
        })
      }
    }
  }
</script>


<style lang="less" scoped>
.wrap {
  p{
    margin-bottom: 10px;
    border-bottom: 1px solid #e7e7e7;
    padding-bottom: 10px;
    display: flex;
    color: #000;
    &:last-child{
      border-bottom: none;
    }
    span{
      color: #000;
      flex: 110px 0 0;
    }
  }
  /deep/ .ant-radio-wrapper {
    color: rgba(0, 0, 0, 1);
  }

  .translate{
    img{
      width: 26px;
      cursor: pointer;
    }
  }
  .my-text::first-line {
    white-space: pre-line;
    position: relative; /* 父元素设置为相对定位 */

  }
  .child {
    position: absolute; /* 子元素设置为绝对定位 */
        bottom: 0; /* 将其放置在父元素的底部 */
        left: 0; /* 将其放置在父元素的左侧 */
  }
}

</style>
