<template>
  <div class="s-page">
    <el-page-header @back="goBack" :content="title"></el-page-header>
    <el-divider></el-divider>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>基本信息</span>
      </div>
      <div class="mymain-container">
        <el-form ref="formData" :rules="rules" :model="formData" label-width="110px" size="small" label-position="left">
          <el-row :gutter="20" justify="start">
            <el-col :span="6">
              <el-form-item label="所属商户" :required="true">
                <el-input
                  type="text"
                  :value="formData.companyWechatName ? formData.companyWechatName : companyName"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" style="height: 51px">
              <el-form-item label="活动名称" prop="promotionActivityId">
                <el-select
                  v-model="formData.active"
                  :disabled="formType != 0"
                  value-key="id"
                  @change="
                    e => {
                      formData.promotionActivityId = e.id
                      formData.activeDate = [e.startTime, e.endTime]
                      this.getActiveDetail(e.id)
                    }
                  "
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option v-for="item in activeList" :key="item.id" :label="item.name" :value="item"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" style="height: 51px">
              <el-form-item label="活动网点" prop="customWebsitName">
                <el-select
                  v-model="formData.customWebsitName"
                  :disabled="formType != 0"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, index) in websitList"
                    :key="index"
                    :label="item.websitName"
                    :value="item.websitName"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" style="margin-bottom: 1px">
              <el-form-item label="活动时间" prop="" class="is-required">
                <el-date-picker
                  style="width: 100%"
                  v-model="formData.activeDate"
                  disabled
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户名称" prop="userName">
                <el-input
                  type="text"
                  :disabled="formType != 0"
                  v-model="formData.userName"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="联系人" prop="linkName">
                <el-input
                  type="text"
                  :disabled="formType != 0"
                  v-model="formData.linkName"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户电话" prop="userMobile">
                <el-input
                  type="text"
                  :disabled="formType != 0"
                  :maxlength="11"
                  v-model="formData.userMobile"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户电话2" prop="userMobile2">
                <el-input
                  type="text"
                  :disabled="formType != 0"
                  v-model="formData.userMobile2"
                  placeholder="请输入电话 (固话加区号)"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="客户地址" prop="userAddress">
                <el-input
                  type="text"
                  v-model="formData.userAddress"
                  :disabled="formType != 0"
                  placeholder="详细地址"
                ></el-input>
              </el-form-item>
            </el-col>
            <template v-if="formType != 0">
              <el-col :span="6">
                <el-form-item label="提交人" prop="createBy">
                  <el-input type="text" v-model="formData.createBy" :disabled="true" placeholder="提交人"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="提交时间" prop="createTime">
                  <el-input
                    type="text"
                    v-model="formData.createTime"
                    :disabled="true"
                    placeholder="提交时间"
                  ></el-input>
                </el-form-item>
              </el-col>
            </template>
          </el-row>
        </el-form>
      </div>
    </el-card>
    <el-card class="box-card" v-if="activeItems.length > 0">
      <div slot="header" class="clearfix">
        <span>报名信息</span>
      </div>
      <div v-for="(item, index) in activeItems" :key="index">
        <div class="picker-container" v-if="item.type == 1 || item.type == 2">
          <div class="label">
            <span v-if="item.isRequire">*</span>{{ item.question }}（{{ { 1: '单选', 2: '多选' }[item.type] }}）
          </div>
          <div
            class="img-list"
            v-if="
              item.answer &&
              item.answer.length > 0 &&
              item.answer[0].option_files &&
              item.answer[0].option_files.length > 0 &&
              item.answer[0].option_files[0].url
            "
          >
            <div
              class="item1"
              :class="it.active ? 'active' : ''"
              v-for="(it, idx) in item.answer"
              :key="idx"
              @click="clickOption(index, idx)"
            >
              <el-image
                v-if="item.answerType != 2"
                class="image"
                :src="$showImgUrl(returnUrl(it))"
                mode="aspectFill"
              ></el-image>
              <div class="text" v-if="item.answerType != 3">{{ it.option_value }}</div>
            </div>
          </div>
          <div class="text-list" v-else>
            <div
              class="item"
              :class="it.active ? 'active' : ''"
              v-for="(it, idx) in item.answer"
              :key="idx"
              @click="clickOption(index, idx)"
            >
              {{ it.option_value }}
            </div>
          </div>
        </div>
        <div class="input-container" v-else-if="item.type == 3">
          <div class="label"><span v-if="item.isRequire">*</span>{{ item.question }}</div>
          <el-input
            type="text"
            v-model="item.inputValue"
            show-word-limit
            :maxlength="item.answer[0].option_limit"
            :disabled="formType != 0"
            :placeholder="`请输入${item.question}`"
          ></el-input>
        </div>
        <div class="input-container" v-else-if="item.type == 4">
          <div class="label"><span v-if="item.isRequire">*</span>{{ item.question }}</div>
          <br />
          <ImageUpload
            :fileList="item.inputValue"
            :limit="Number(item.answer[0].option_limit)"
            :isEdit="formType == 0"
            :fileType="['image']"
          />
        </div>
        <div class="input-container" v-else>
          <div class="label"><span v-if="item.isRequire">*</span>{{ item.question }}</div>
          <br />
          <ImageUpload
            :fileList="item.inputValue"
            :limit="Number(item.answer[0].option_limit)"
            :isEdit="formType == 0"
            :fileType="['video']"
          />
        </div>
      </div>
    </el-card>
    <el-card class="box-card" v-if="formType != 0">
      <div slot="header" class="clearfix">
        <span>跟进记录</span>
      </div>
      <div class="mymain-container">
        <el-form ref="formData" :model="formData" label-width="110px" size="small" label-position="left">
          <el-row :gutter="20" justify="start">
            <el-col :span="24">
              <el-form-item label="最新跟进结果" prop="status" class="is-required">
                <el-radio-group v-model="formData.status">
                  <el-radio :disabled="status == 'END'" label="ING">继续跟进</el-radio>
                  <el-radio :disabled="status == 'END'" label="END">无需跟进</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="备注"
                prop="remark"
                :rules="[{ required: true, message: `请输入备注内容`, trigger: 'blur' }]"
              >
                <el-input
                  type="textarea"
                  :rows="3"
                  :disabled="status == 'END'"
                  v-model="formData.remark"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="table">
        <div>跟进记录</div>
        <br />
        <el-table :data="formData.records" element-loading-text="Loading" border fit highlight-current-row stripe>
          <el-table-column prop="status" label="跟进结果" align="center">
            <template slot-scope="scope">
              {{ scope.row.status == 'ING' ? '继续跟进' : scope.row.status == 'END' ? '无需跟进' : '' }}
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" align="center"></el-table-column>
          <el-table-column prop="createBy" align="center" label="跟进人"></el-table-column>
          <el-table-column prop="createTime" align="center" label="跟进时间"></el-table-column>
        </el-table>
      </div>
    </el-card>
    <div class="page-footer">
      <div class="footer">
        <el-button size="small" type="info" @click="goBack">返回</el-button>
        <el-button v-if="formType == 0 || status == 'ING'" size="small" type="primary" @click="submit()"
          >提交</el-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import ImageUpload from '@/components/file-upload'
import { getDetail, add, follow, getActiveList, getActiveDetail } from '@/api/activityOrder'
export default {
  components: { ImageUpload },
  props: ['id', 'title', 'formType', 'activeId'],
  data() {
    return {
      dataList: [],
      activeList: [],
      activeItems: [],
      websitList: [],
      formData: {
        active: {},
        activeDate: [],
        promotionActivityId: '',
        customWebsitName: '',
        userName: '',
        linkName: '',
        userMobile: '',
        userMobile2: '',
        userAddress: '',
        status: '',
        remark: ''
      },
      status: '',
      companyName: JSON.parse(localStorage.getItem('greemall_user')).companyName,
      rules: {
        userMobile: [
          { required: true, message: `请输入客户电话`, trigger: 'blur' },
          { required: true, message: `请输入客户电话`, trigger: 'change' },
          { pattern: /^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$/, message: '电话号码格式不正确', trigger: 'blur' }
        ],
        userName: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
        linkName: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
        userAddress: [{ required: true, message: '请输入客户地址', trigger: 'blur' }],
        promotionActivityId: [{ required: true, message: '请选择活动名称', trigger: 'change' }]
      }
    }
  },
  computed: {
    returnUrl() {
      return function (it) {
        return it.option_files.length > 0 ? it.option_files[0].url : ''
      }
    }
  },
  created() {
    if (this.id) {
      this.getDetail()
    }
    if (this.activeId) {
      this.formData.active = { id: this.activeId }
      this.formData.promotionActivityId = this.activeId
      if (this.formType == 0) {
        this.getActiveDetail(this.activeId)
      }
    }
    this.getActiveList()
  },
  methods: {
    // 返回
    goBack() {
      this.$emit('back')
    },
    async getDetail() {
      const that = this
      getDetail({ promotionActivityId: this.id }).then(async res => {
        Object.assign(this.formData, res.data, {
          active: { id: res.data.promotionQuestionnaireId }
        })
        this.websitList = res.data.promotionQuestionnaireQrcodes
        this.status = res.data.status
        res.data.items.forEach(item => {
          item.answer = JSON.parse(item.answer)

          item.answer.forEach(it => {
            if (item.type == 3) {
              item.inputValue = it.option_value
            } else if (item.type == 4 || item.type == 5) {
              let img = []
              it.option_value.forEach(t => {
                img.push({ url: t })
              })
              console.log(it.option_value, img)
              item.inputValue = img
            }
          })
        })
        this.activeItems = res.data.items
        getActiveDetail({ id: res.data.promotionQuestionnaireId }).then(res => {
          this.formData.activeDate = [res.data.startTime, res.data.endTime]
        })
        // this.getActiveDetail(res.data.promotionQuestionnaireId,res.data.items)
      })
    },
    getActiveList() {
      getActiveList({ pageNum: 1, pageSize: -1, status: 1 }).then(res => {
        this.activeList = res.data.records
      })
    },
    getActiveDetail(id, items) {
      getActiveDetail({ id }).then(res => {
        this.formData.activeDate = [res.data.startTime, res.data.endTime]
        this.websitList = res.data.promotionQuestionnaireQrcodes
        res.data.promotionQuestionnaireItems.forEach((item, index) => {
          item.answer = JSON.parse(item.answer)
          if (items) {
            item.answer.forEach(it1 => {
              items.forEach(it2 => {
                JSON.parse(it2.answer).forEach(t => {
                  if (item.id == it2.id && t.active && it1.option_value == t.option_value) {
                    console.log(t.option_value)
                    it1.active = true
                  }
                  if (it2.type == 3) {
                    item.inputValue = t.option_value
                  } else if (it2 == 4 || it2 == 5) {
                    item.inputValue = [{ url: t.option_value }]
                  }
                })
              })
            })
          } else {
            if (item.type == 4 || item.type == 5) {
              item.inputValue = []
            } else {
              item.inputValue = ''
            }
            item.answer.forEach(it => {
              it.active = false
            })
          }
        })
        this.activeItems = res.data.promotionQuestionnaireItems
        console.log(this.activeItems, 111)
      })
    },
    clickOption(index, idx) {
      if (this.id) {
        return false
      }
      // 单选题
      if (this.activeItems[index].type == 1) {
        this.activeItems[index].answer.forEach((item, ind_) => {
          this.activeItems[index].answer.splice(ind_, 1, {
            ...item,
            active: ind_ == idx ? (this.activeItems[index].isRequire ? true : !item.active) : false
          })
        })
      }
      // 多选题
      else {
        this.activeItems[index].answer.splice(idx, 1, {
          ...this.activeItems[index].answer[idx],
          active: !this.activeItems[index].answer[idx].active
        })
      }
    },
    submit() {
      this.$refs.formData.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          if (this.formType == 0) {
            for (let i = 0; i < this.activeItems.length; i++) {
              if (this.activeItems[i].isRequire) {
                // 单选题多选题
                if (
                  (this.activeItems[i].type == 1 || this.activeItems[i].type == 2) &&
                  this.activeItems[i].answer.every(o => !o.active)
                ) {
                  return this.$message.warning(`请选择${this.activeItems[i].question}`)
                }
                // 填写题
                if (this.activeItems[i].type == 3 && !this.activeItems[i].inputValue) {
                  return this.$message.warning(`请输入${this.activeItems[i].question}`)
                }
                // 图片视频
                if (
                  (this.activeItems[i].type == 4 || this.activeItems[i].type == 5) &&
                  this.activeItems[i].inputValue.length == 0
                ) {
                  return this.$message.warning(`请上传${this.activeItems[i].question}`)
                }
              }
            }
            // 生成题目提交信息
            let items = []
            let activeItems = JSON.parse(JSON.stringify(this.activeItems))
            for (let index = 0; index < activeItems.length; index++) {
              // 单选题多选题
              if (activeItems[index].type == 1 || activeItems[index].type == 2) {
                // activeItems[index].answer = activeItems[index].answer.filter(o => o.active);
                activeItems[index].answer = JSON.stringify(activeItems[index].answer)
                items.push(activeItems[index])
              }
              // 填写题
              if (activeItems[index].type == 3) {
                activeItems[index].answer[0].option_value = activeItems[index].inputValue
                activeItems[index].answer = JSON.stringify(activeItems[index].answer)
                items.push(activeItems[index])
              }
              // 图片视频
              if (activeItems[index].type == 4 || activeItems[index].type == 5) {
                let option_value = []
                activeItems[index].inputValue.forEach(item => {
                  option_value.push(item.url)
                })
                activeItems[index].answer[0].option_value = option_value
                activeItems[index].answer = JSON.stringify(activeItems[index].answer)
                items.push(activeItems[index])
              }
            }
            add({
              promotionQuestionnaireId: this.formData.promotionActivityId,
              userName: this.formData.userName,
              linkName: this.formData.linkName,
              userMobile: this.formData.userMobile,
              userMobile2: this.formData.userMobile2,
              userAddress: this.formData.userAddress,
              customWebsitName: this.formData.customWebsitName,
              items
            }).then(res => {
              if (res.code == 200) {
                this.$message.success('提交成功！')
                this.goBack()
              }
            })
          } else {
            follow({
              ids: [this.id],
              status: this.formData.status,
              remark: this.formData.remark
            }).then(res => {
              if (res.code == 200) {
                this.dataList = []
                this.$message.success('提交成功！')
                this.goBack()
              }
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped="scoped" lang="scss">
.s-page {
  padding: 20px;
  background-color: #ffffff;
}
.page-footer {
  height: 70px;
}
.input-container {
  margin-top: 20px;
  .label {
    font-size: 14px;
    font-weight: bold;
    span {
      color: red;
    }
  }
}
.picker-container {
  margin-top: 20px;
  .label {
    font-size: 14px;
    font-weight: bold;
    span {
      color: red;
    }
  }
  .text-list {
    display: flex;
    flex-wrap: wrap;
    .item {
      margin-top: 20px;
      margin-right: 20px;
      height: 40px;
      border-radius: 30px;
      background: #f5f5f5;
      font-size: 14px;
      display: flex;
      align-items: center;
      justify-content: center;
      box-sizing: border-box;
      cursor: pointer;
      padding: 0 40px;
      &.active {
        border: 1px solid #f6390d;
        color: #f6390d;
        background: #ffffff;
      }
    }
  }
  .img-list {
    display: flex;
    flex-wrap: wrap;
    .item,
    .item1 {
      margin-top: 10px;
      margin-right: 10px;
      border-radius: 20px;
      height: 40px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      box-sizing: border-box;
      padding: 0 40px;
      background-color: #f3f3f3;
      cursor: pointer;
      .image {
        width: 100%;
        height: 60px;
      }
      .text {
        font-size: 14px;
      }
      &.active {
        border: 1px solid #f6390d;
        background-color: #ffffff;
        .text {
          color: #f6390d;
        }
      }
    }
    .item1 {
      height: 130px;
      border-radius: 6px;
      padding: 6px;
      .image {
        width: 120px;
        height: 100px;
      }
    }
  }
}
.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 1;
  width: 100%;
  background: #fff;
  padding: 15px 40px;
  box-sizing: border-box;
  transition: all 0.28s;
  text-align: right;
  box-shadow: 0 2px 5px 0 rgb(0 0 0 / 50%), 0 2px 5px 0 rgb(0 0 0 / 10%);

  &.hideSidebar {
    margin-left: 54px;
    width: calc(100vw - 54px);
  }

  &.openSidebar {
    margin-left: 210px;
    width: calc(100vw - 210px);
  }

  .tips {
    font-size: 12px;
    color: red;
    margin-top: 10px;
  }
}
</style>
