<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="销售公司" prop="companyId">
        <el-select v-model="queryParams.companyId" placeholder="销售公司" @change="changeCorpOrCompany()" size="small">
          <el-option
            v-for="dict in companyList"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="企微主体" prop="corpId">
        <el-select v-model="queryParams.corpId" placeholder="企微主体" @change="changeCorpOrCompany()" size="small">
          <el-option
            v-for="dict in myQwCompanyList"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="使用的成员" prop="qwUserIds">
        <el-select v-model="queryParams.qwUserIds" filterable  clearable placeholder="公司员工" size="small">
          <el-option
            v-for="dict in companyUserList"
            :key="dict.id"
            :label="dict.qwUserName+'('+dict.qwUserId+')'"
            :value="dict.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否开启分时段" prop="isDayparting">
        <el-select v-model="queryParams.isDayparting" placeholder="请选择" clearable size="small">
          <el-option v-for="dict in allowSelectOptions" :key="dict.dictValue" :label="dict.dictLabel"  :value="dict.dictValue"/>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable size="small"
                        v-model="queryParams.createTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间" prop="updateTime">
        <el-date-picker clearable size="small"
                        v-model="queryParams.updateTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择更新时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="是否发送欢迎语" prop="isSendMsg">
        <el-select v-model="queryParams.isSendMsg" placeholder="请选择" clearable size="small" >
          <el-option v-for="dict in allowSelectOptions" :key="dict.dictValue" :label="dict.dictLabel"  :value="dict.dictValue"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="friendWelcomeList" border>
      <el-table-column label="id" align="center" prop="id" width="180"/>
      <el-table-column label="销售公司" align="center" prop="companyName"/>
      <el-table-column label="企微主体" align="center" prop="corpName"/>
      <el-table-column label="标题" align="center" prop="welcomeTitle"/>
      <el-table-column label="消息内容" align="left" prop="welcomeText"  width="400px" >
        <template slot-scope="scope">
          <span style="color:rgb(19, 154, 50);" v-if="scope.row.isDayparting==='1'">[共 {{JSON.parse(scope.row.daypartingItemlist).length+1}} 时段]</span>
          <span style="color:rgb(19, 154, 50);" v-else >[默认时段]</span>
          <el-tooltip class="item" effect="dark" :content="scope.row.welcomeText" placement="top">
            <div style="display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; overflow: hidden; text-overflow: ellipsis;">
              <span>{{ scope.row.welcomeText }}</span>
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="使用成员" align="center" prop="qwUserIds">
        <template slot-scope="scope">
          <div v-for="id in JSON.parse(scope.row.qwUserIds)" :key="id" style="display: inline;" class="text-container">
            <el-tag type="success" v-for="list in companyUserList" :key="list.qwUserId" style="margin: 3px;" v-if="list.id==id">{{list.qwUserName}}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="是否开启分时段" align="center" prop="isDayparting">
        <template slot-scope="scope">
          <dict-tag :options="allowSelectOptions" :value="scope.row.isDayparting"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否发送欢迎语" align="center" prop="isSendMsg" >
        <template slot-scope="scope">
          <dict-tag :options="allowSelectOptions" :value="scope.row.isSendMsg"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleDetail(scope.row)"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改好友欢迎语对话框 -->
    <el-dialog :title="friendWelcomeDialog.title" :visible.sync="friendWelcomeDialog.visible" v-loading="friendWelcomeDialog.loading" width="1200px" append-to-body>
      <div style="width: 1130px" class="app-container">
        <div>
          <span style="font-size: 15px">基础信息</span>
          <el-divider></el-divider>
        </div>
        <el-form ref="form" :model="friendWelcomeDialog.friendWelcomeInfo" :disabled="true" label-width="120px">
          <el-form-item label="使用成员：" style="margin-top: 2%">
            <div>
              <el-tag
                style="margin-left: 5px"
                size="medium"
                :key="list.id"
                v-for="list in userSelectList"
                closable
                :disable-transitions="false">
                {{list.qwUserName}}({{list.nickName}})
              </el-tag>
            </div>
          </el-form-item>
          <!-- 新增整体标题 -->
          <el-form-item label="标题：" prop="welcomeTitle">
            <el-input v-model="friendWelcomeDialog.friendWelcomeInfo.welcomeTitle" placeholder="请输入欢迎语标题"/>
            <el-alert style="margin-top: 8px;height: 30px"
                      title="此标题仅用于欢迎语的用途区分"
                      type="info"
                      :closable="false"
                      show-icon>
            </el-alert>
          </el-form-item>
          <el-form-item label="是否发送欢迎语">
            <el-switch
              v-model="friendWelcomeDialog.friendWelcomeInfo.isSendMsg"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-value="1"
              inactive-value="2">
            </el-switch>
            <span v-if="friendWelcomeDialog.friendWelcomeInfo.isSendMsg == '1'" style="margin-left: 10px;color: #13ce66">允许</span>
            <span v-if="friendWelcomeDialog.friendWelcomeInfo.isSendMsg == '2'" style="margin-left: 10px;color: #ff4949">不允许</span>

          </el-form-item>
          <div>
            <span style="font-size: 15px">发送欢迎语</span>
            <el-divider></el-divider>
          </div>
          <el-form-item label="默认欢迎语：" prop="welcomeText">
            <el-input v-model="friendWelcomeDialog.friendWelcomeInfo.welcomeText" type="textarea"  :rows="12" maxlength="1300" show-word-limit placeholder="请输入消息内容"/>
            <!-- 附件和链接列表 -->
            <el-row>
              <el-col>
                <div v-for="(item, index) in friendWelcomeDialog.friendWelcomeInfo.attachments" :key="index" style="background-color: #f5f7fa;padding: 5px;border: 1px solid  #d9d9d9;">
                  <div slot="header" style="display: flex;justify-content: space-between;align-items: center; ">
                    <div style="flex: 1;">
                      <span v-if="item.msgtype === 'image'">【图片】: {{ item.image.pic_url }}</span>
                      <span v-if="item.msgtype === 'video'">【视频】: {{ item.video.url }}</span>
                      <span v-if="item.msgtype === 'link'">【链接】: {{ item.link.title }}-{{item.link.desc}}</span>
                      <span v-if="item.msgtype === 'miniprogram'">【小程序】: {{ item.miniprogram.title }}</span>
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item label="分时段欢迎语">
            <el-switch
              v-model="friendWelcomeDialog.friendWelcomeInfo.isDayparting"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-value="1"
              inactive-value="2">
            </el-switch>
            <span v-if="friendWelcomeDialog.friendWelcomeInfo.isDayparting == '1'" style="margin-left: 10px;color: #13ce66">已启用</span>
            <span v-if="friendWelcomeDialog.friendWelcomeInfo.isDayparting == '2'" style="margin-left: 10px;color: #ff4949">已禁用</span>
          </el-form-item>

          <el-form-item v-if="friendWelcomeDialog.friendWelcomeInfo.isDayparting == '1'" >
            <div style="background-color:#ecf8fe;width: 100%;border: 1px solid #dcdfe6">
              <span style="margin-left:20px;font-size: 15px;display: block" >注意：1、员工上下班不同时间段可设置不同欢迎语;</span>
              <span style="margin-left:65px;font-size: 15px;display: block" >2、分时段之外的时间将发送已允许的默认欢迎语。</span>
              <span style="margin-left:65px;font-size: 15px;display: block" >3、不设置分时段欢迎语则使用已允许的默认欢迎语</span>
              <span style="margin-left:65px;font-size: 15px;display: block" >4、若员工没有设置过欢迎语则不会发送</span>
            </div>
          </el-form-item>
          <el-form-item v-if="friendWelcomeDialog.friendWelcomeInfo.isDayparting == '2'">
            <div style="background-color:#ecf8fe;width: 100%;border: 1px solid #dcdfe6">
              <span style="margin-left:20px;font-size: 15px;display: block" >注意：1、新建欢迎语最多可发送1条文字消息和9个附件;</span>
              <span style="margin-left:65px;font-size: 15px;display: block" >2、文字消息和附件不能同时为空，当两者均填写时用户会收到多条消息;</span>
              <span style="margin-left:65px;font-size: 15px;display: block" >3、欢迎语将在客户加为好友后20秒内下发，因网络延迟可能造成发送不成功</span>
            </div>
          </el-form-item>
          <div  v-if="friendWelcomeDialog.friendWelcomeInfo.isDayparting == '1'"  v-for="(item, index) in friendWelcomeDialog.friendWelcomeInfo.daypartingItemlist"    :key="index" >
            <el-form-item :label="`时段 ${index + 1}：`">
              <el-row>
                <el-col style="width: 965px">
                  <div style="background-color: #fbfbfb;padding: 10px;  border: 1px solid #e6e6e6; margin-bottom: 20px;">
                    <el-form ref="friendWelcomeItemForm" :disabled="true" :model="item">
                      <div style="display: flex; gap: 10px;">
                        <el-form-item label="发起时间:" prop="week" style="flex: 8;">
                          <el-select v-model="item.week" remote multiple placeholder="请选择" filterable style="width: 580px">
                            <el-option
                              v-for="dict in weekOptions"
                              :key="dict.value"
                              :label="dict.label"
                              :value="dict.value">
                            </el-option>
                          </el-select>
                        </el-form-item>
                        <el-form-item prop="startTime" style="flex: 1;">
                          <el-time-select style="width: 120px;"
                                          placeholder="起始时间"
                                          v-model="item.startTime"
                                          :picker-options="{
                                            start: '00:00',
                                            step: '00:15',
                                            end: '24:00'
                                          }">
                          </el-time-select>
                        </el-form-item>
                        <el-form-item prop="endTime" style="flex: 1;">
                          <el-time-select style="width: 120px;"
                                          placeholder="结束时间"
                                          v-model="item.endTime"
                                          :picker-options="{
                                            start: '00:00',
                                            step: '00:15',
                                            end: '24:00',
                                            minTime: item.startTime
                                          }">
                          </el-time-select>
                        </el-form-item>
                      </div>

                      <el-form-item style="margin-top: 20px" prop="welcomeText">
                        <el-input v-model="item.welcomeText" type="textarea" :rows="12" maxlength="1300" show-word-limit placeholder="请输入消息内容"/>
                        <!-- 附件和链接列表 -->
                        <el-row>
                          <el-col>
                            <div v-for="(attachment, attachIndex) in item.attachments" :key="attachIndex" style="background-color: #f5f7fa;padding: 5px;border: 1px solid  #d9d9d9;">
                              <div slot="header" style="  display: flex;justify-content: space-between;align-items: center; ">
                                <div style="flex: 1;">
                                  <span v-if="attachment.msgtype === 'image'">【图片】: {{ attachment.image.pic_url }}</span>
                                  <span v-if="attachment.msgtype === 'video'">【视频】: {{ attachment.video.url }}</span>
                                  <span v-if="attachment.msgtype === 'link'">【链接】: {{ attachment.link.title }}-{{attachment.link.desc}}</span>
                                  <span v-if="attachment.msgtype === 'miniprogram'">【小程序】: {{ attachment.miniprogram.title }}</span>
                                </div>
                              </div>
                            </div>
                          </el-col>
                        </el-row>
                      </el-form-item>
                    </el-form>
                  </div>
                </el-col>
              </el-row>
            </el-form-item>
          </div>

        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getFriendWelcome, listFriendWelcome } from '@/api/qw/friendWelcome'
import { allList } from '@/api/company/company'
import { getMyQwCompanyList, getQwAllUserList } from '@/api/qw/user'

export default {
  name: "FriendWelcome",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企微主体列表
      myQwCompanyList: [],
      companyList: [],
      companyUserList: [],
      allowSelectOptions: [],
      friendWelcomeList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyId: null,
        corpId: null,
        qwUserIds: [],
        isDayparting: null,
        createTime: null,
        updateTime: null,
        isSendMsg: null,
      },
      userSelectList: [],
      friendWelcomeDialog: {
        visible: false,
        loading: false,
        title: "详情",
        friendWelcomeInfo: {},
      },
      weekOptions: [
        { value: 1, label: '星期一' },
        { value: 2, label: '星期二' },
        { value: 3, label: '星期三' },
        { value: 4, label: '星期四' },
        { value: 5, label: '星期五' },
        { value: 6, label: '星期六' },
        { value: 7, label: '星期天' }
      ],
    }
  },
  async created() {
    this.getDicts("sys_qw_allow_select").then(response => {
      this.allowSelectOptions = response.data;
    });
    const [allRes, myRes] = await Promise.all([
      allList(),
      getMyQwCompanyList()
    ]);

    this.companyList = allRes.rows;
    this.myQwCompanyList = myRes.data;

    this.queryParams.companyId = this.companyList[0].dictValue
    this.queryParams.corpId = this.myQwCompanyList[0].dictValue

    this.changeCorpOrCompany()
    this.getList();
  },
  methods: {
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.companyUserList = []

      this.queryParams.companyId = this.companyList[0].dictValue
      this.queryParams.corpId = this.myQwCompanyList[0].dictValue
      this.changeCorpOrCompany()
      this.handleQuery();
    },
    getList() {
      this.loading = true;
      listFriendWelcome(this.queryParams).then(response => {
        this.friendWelcomeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    changeCorpOrCompany() {
      if (this.queryParams.corpId != null && this.queryParams.companyId != null) {
        const params = {
          companyId: this.queryParams.companyId,
          corpId: this.queryParams.corpId
        }
        getQwAllUserList(params).then(response => {
          this.companyUserList = response.data;
        });
      }
    },
    handleDetail(row) {
      getFriendWelcome(row.id).then(response => {
        let data = response.row

        const params = {
          companyId: data.companyId,
          corpId: data.corpId
        }
        getQwAllUserList(params).then(res => {
          this.userSelectList = res.data.filter(item => {
            return data.qwUserIds.includes(item.id)
          })
        })

        // 转换 attachments
        if (typeof data.attachments === 'string') {
          data.attachments = JSON.parse(data.attachments);
        }

        // 转换 daypartingItemlist
        if (typeof data.daypartingItemlist === 'string') {
          data.daypartingItemlist = JSON.parse(data.daypartingItemlist);
        }

        // 转换 daypartingItemlist 中的每个项目的 attachments 和 week
        if (Array.isArray(data.daypartingItemlist)) {
          data.daypartingItemlist = data.daypartingItemlist.map(item => {
            return {
              ...item,
              attachments: typeof item.attachments === 'string' ? JSON.parse(item.attachments) : item.attachments,
              week: typeof item.week === 'string' ? JSON.parse(item.week) : item.week
            };
          });
        }
        this.friendWelcomeDialog.friendWelcomeInfo = data
        this.friendWelcomeDialog.visible = true
      })
    },
  },
}
</script>

<style scoped>

</style>
