<template>
  <div class="send-msg">
    <h1>群发消息</h1>
    <Form ref="send" :model="send" :rules="ruleValidate" :label-width="112">
      <FormItem label="用户：" prop="sendway">
          <RadioGroup v-model="send.sendway">
            <Radio label="1">
                <span>全部用户</span>
            </Radio>
            <Radio label="2" style="margin-left:20px">
                <span>convertlab用户分组</span>
            </Radio>
          </RadioGroup>
      </FormItem>
      <FormItem label="发送用户：" prop="userGroupName" v-if="send.sendway==2">
        convertlab用户分组同步
        <Button type="primary" size="small" @click="refreshed" style="margin: 0 40px">刷新分组</Button>
        <!-- <RadioGroup v-model="msgRadio">
          <Radio label="1">
              <span>后台群组</span>
          </Radio>
          <Radio label="2" style="margin-left:20px">
              <span>新用户</span>
          </Radio>
        </RadioGroup> -->
        <!-- <div v-show="groupData.length" style="border-bottom: 1px solid #e9e9e9;padding-bottom:6px;margin-bottom:6px;">
            <Checkbox
                :indeterminate="indeterminate"
                :value="checkAll"
                @click.prevent.native="handleCheckAll">全部用户</Checkbox>
        </div> -->
        <CheckboxGroup v-model="send.userGroupName" @on-change="checkGroup" v-show="groupData.length">
          <Checkbox v-for="item in groupData" :key="item.id" :label="item.name">
              <span>{{item.name}}</span>
          </Checkbox>
        </CheckboxGroup>
      </FormItem>
      <FormItem label="消息类型：" prop="msgType" style="width:300px">
          <Select v-model="send.msgType" placeholder="请选择消息类型">
              <Option v-for="item in messageTypeList" :value="item.msg_type" :key="item.msg_type">{{ item.name }}</Option>
          </Select>
      </FormItem>
      <FormItem label="消息标题：" prop="title">
          <Input
            v-model="send.title"
            type="text"
            :maxlength="30"
            placeholder="请输入消息标题（最多30个字）"
          ></Input>
      </FormItem>
      <FormItem label="消息内容：" prop="content">
          <Input v-model="send.content" type="textarea" :autosize="{minRows: 3,maxRows: 5}" placeholder="请输入消息内容（最多200个字）" :maxlength="200"></Input>
      </FormItem>
      <FormItem label="内容链接："><br />
        <div class="link-url">
          <span>PC</span>
          <Input
            v-model="send.link"
            type="text"
            placeholder="请输入PC端内容链接"
          ></Input>
        </div>
        <div class="link-url">
          <span>安卓</span>
          <Input
            v-model="send.androidUrl"
            type="text"
            placeholder="请输入安卓端内容链接"
          ></Input>
        </div>
        <div class="link-url">
          <span>苹果</span>
          <Input
            v-model="send.iosUrl"
            type="text"
            placeholder="请输入苹果端内容链接"
          ></Input>
        </div>
        <div class="link-url">
          <span>微信</span>
          <Input
            v-model="send.weChatUrl"
            type="text"
            placeholder="请输入微信端内容链接"
          ></Input>
        </div>
      </FormItem>
<!--      <FormItem label="展示样式：" style="width:440px"><br/>-->
<!--        <div class="show_style">-->
<!--          <div class="show_top show_common">-->
<!--            <div class="show_label">在前端是否展示为浮标</div>-->
<!--            <Select v-model="send.showBuoy" placeholder="请选择是否展示为浮标">-->
<!--                <Option v-for="item in showSelect" :value="item.v" :key="item.v">{{ item.n }}</Option>-->
<!--            </Select>-->
<!--          </div>-->
<!--          <div class="show_bot show_common">-->
<!--            <div class="show_label">展示文案为</div>-->
<!--            <Input-->
<!--              v-model="send.showContent"-->
<!--              type="text"-->
<!--              class="show_text"-->
<!--              placeholder="请输入展示文案"-->
<!--            ></Input>-->
<!--          </div>-->
<!--        </div>-->
<!--      </FormItem>-->
      <FormItem label="发送时效：" prop="sendMode">
          <RadioGroup v-model="send.sendMode">
            <Radio label="1">
                <span>定时</span>
            </Radio>
            <Radio label="2" style="margin-left:20px">
                <span>实时</span>
            </Radio>
          </RadioGroup>
      </FormItem>
      <FormItem label="发送时间：" prop="sendTime" style="width:600px" v-show="send.sendMode=='1'">
          <date-sigle ref="sigleRef3" :dateType="'datetime'" :formated="'yyyy-MM-dd HH:mm'" :placeholderd="'请选择发送时间'" @startDate="sendDate" :overTime="0"></date-sigle>
      </FormItem>
      <FormItem label="App端打开菜单：" prop="menuname" style="width:300px">
        <Select v-model="send.menuname" placeholder="APP端消息进入展示所属菜单" filterable clearable>
          <Option v-for="item in menuList" :value="item.key" :key="item.key">{{ item.label }}</Option>
        </Select>
      </FormItem>
      <FormItem>
          <Button type="primary" :class="{'is-active':isDis}" @click="sendSub('send')" style="width:100px">保存</Button>
          <Button @click="sendCancel('send')" style="width: 100px;margin-left: 8px">取消</Button>
      </FormItem>
    </Form>
  </div>
</template>

<script>
import dateSigle from '@/components/dateSigle'
import { mapGetters } from 'vuex'
export default {
  components: {
    dateSigle
  },
  computed: {
    ...mapGetters(['messageTypeList'])
  },
  created() {
    this.refreshed()
    if(this.messageTypeList.length === 0) {
      this.$store.dispatch('getMessageType')
    }
  },
  methods: {
    msgBack() {
      this.$request('/message/messageDetails').data({
        id: this.$route.query.id
      }).success((res) => {
        if (res.status == 'success') {
          Object.keys(this.send).forEach(key => {
            this.send[key] = res.data[key]
          })
          // if(res.data.send_usergroup_id === 'all_user'){ //全选
          //   this.checkAll = true
          //   let arrs = [], arrs1 = []
          //   this.groupData.forEach(v => {
          //     arrs.push(v.name)
          //     arrs1.push(v.id)
          //   })
          //   this.send.userGroupId = arrs1
          //   this.send.userGroupName = arrs
          // } else {
          //   this.indeterminate = true
          //   this.send.userGroupId = res.data.send_usergroup_id?res.data.send_usergroup_id.split(','):[]
          //   this.send.userGroupName = res.data.send_usergroup_name?res.data.send_usergroup_name.split(','):[]
          // }
          if(res.data.send_usergroup_id === 'all_user'){
            this.send.sendway = '1'
          } else {
            this.send.sendway = '2'
            this.send.userGroupId = res.data.send_usergroup_id?res.data.send_usergroup_id.split(','):[]
            this.send.userGroupName = res.data.send_usergroup_name?res.data.send_usergroup_name.split(','):[]
          }
          this.send.msgType = res.data?.msg_type?.toString()
          this.send.sendMode = String(res.data.send_mode)
          this.send.sendTime = res.data.send_time
          this.$refs.sigleRef3.dataVals = res.data.send_time
        }
      }).get()
    },
    inited() {
      this.$refs.sigleRef3.initd()
      this.isDis = false
      // this.checkAll = false
      // this.indeterminate = false
      Object.keys(this.send).forEach( key => {
        if (key == 'userGroupName') {
          this.send[key] = []
        } else {
          this.send[key] = ''
        }
      })
    },
    refreshed() {
      this.$request('/message/getGroup').data().success((res) => {
        if (res.status == 'success') {
          this.groupData = res.data
          if (this.$route.query.id) {
            this.msgBack()
          }
        }
      }).get()
    },
    handleCheckAll () {
        if (this.indeterminate) {
            this.checkAll = false
        } else {
            this.checkAll = !this.checkAll
            this.send.userGroupId = []
        }
        this.indeterminate = false
        if (this.checkAll) {
          const arrs = [], arrs1 = []
          this.groupData.forEach(v => {
            arrs.push(v.name)
            arrs1.push(v.id)
          })
          this.send.userGroupId = arrs1
          this.send.userGroupName = arrs
        } else {
          this.send.userGroupId = []
          this.send.userGroupName = []
        }
        this.$refs.send.validateField('userGroupName')

    },
    checkGroup(data) {
      const arrs = []
      this.groupData.forEach(v => {
        data.forEach(i => {
          if (i == v.name) {
            arrs.push(v.id)
          }
        })
      })
      this.send.userGroupId = arrs
      if (data.length === this.groupData.length) {
          this.indeterminate = false
          this.checkAll = true
      } else if (data.length > 0) {
          this.indeterminate = true
          this.checkAll = false
      } else {
          this.indeterminate = false
          this.checkAll = false
      }

    },
    sendDate(val) {
      this.send.sendTime = val
    },
    sendSub(name) {
      let rout = this.$route.query.id
      let obj = {
        id: rout ? rout : '',
        userGroupId: this.send.sendway == 1 ? 'all_user' : String(this.send.userGroupId),
        userGroupName:this.send.sendway == 1  ? '全部用户' : String(this.send.userGroupName),
        msgType: Number(this.send.msgType),
        title: this.send.title,
        content: this.send.content,
        link: this.send.link,
        androidUrl: this.send.androidUrl,
        iosUrl: this.send.iosUrl,
        weChatUrl: this.send.weChatUrl,
        sendMode: this.send.sendMode,
        showBuoy: this.send.showBuoy,
        showContent: this.send.showContent,
        sendTime: this.send.sendMode=='1'?this.send.sendTime:'',
        menuname: this.send.menuname
      }
      console.log(obj)
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.isDis = true
          setTimeout(() => {
            if (rout) {
              this.inited()
              this.$refs[name].resetFields()
              this.$Message.success('修改成功!')
              // dataManage
              this.$router.push('/msgManage/sentList')
            }
          }, 600)
          setTimeout(() => {
            this.isDis = false
          }, 1000)

          this.$request('/message/messageSave').data(obj).success((res) => {
            if (res.status === 'success') {
              this.inited()
              this.$refs[name].resetFields()
            }

          }).error(() => {
              this.isDis = false
          }).post()
          this.$Message.success('发送成功!')
        }
      })
    },
    sendCancel(name) {
      let rout = this.$route.query.id
      if (rout) {
        this.$router.push('/msgManage/sentList')
      } else {
        this.inited()
        this.$refs[name].resetFields()
      }
    }
  },
  data () {
    return {
      isDis: false,
      // msgRadio: 1,
      // showSelect: [
      //   {v: 1, n: '是'},
      //   {v: 0, n: '否'}
      // ],
      indeterminate: false, //半选
      checkAll: false, // 全选
      groupData: [],
      menuList: [
        {
          key: 'search',
          label: '首页'
        },
        {
          key: 'subscribe',
          label: '订阅'
        },
        {
          key: 'message',
          label: '消息'
        },
        {
          key: 'box',
          label: '百宝箱'
        },
        {
          key: 'me',
          label: '我的'
        },
        {
          key: 'other',
          label: '新的 webview'
        }
      ],
      send: {
        userGroupId: [],
        userGroupName: [],
        msgType: '',
        title: '',
        content: '',
        link: '',
        androidUrl: '',
        iosUrl: '',
        weChatUrl: '',
        showBuoy: 0,
        sendMode: '',
        sendway:'',
        showContent: '',
        sendTime: '',
        menuname: 'message'
      },
      ruleValidate: {
        sendway: [{ required: true, message: '请选择用户类型', trigger: 'change'}],
        userGroupName: [
          { required: true, type: 'array', min: 1, message: '请选择发送用户', trigger: 'change' }
        ],
        msgType: [
          { required: true, message: '请选择消息类型', trigger: 'change'}
        ],
        title: [
          { required: true, message: '消息标题不能为空', trigger: 'blur'},
          { type: 'string', max: 30, message: '最多30个字', trigger: 'blur'}
        ],
        content: [
          { required: true, message: '请输入消息内容', trigger: 'blur'},
          { type: 'string', max: 200, message: '最多200个字', trigger: 'blur'}
        ],
        sendMode: [
          { required: true, message: '请选择发送时效', trigger: 'change'}
        ]
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .send-msg {
    display: flex;
    flex-direction: column;
    align-items: center;
    h1 {
      width: 90%;
      font-size:24px;
      color:#3f4047;
      padding: 10px 0 20px 10px;
    }
    .ivu-form {
      width: 90%;
      background: #fff;
      padding: 20px;
      :v-deep .ivu-form-item-label {
        text-align: right;
      }
      ::v-deep .ivu-input{
        width: 660px;
      }
      ::v-deep {
        .show_text{
          .ivu-input{
            width: 620px;
          }
        }
      }
    }
    .link-url {
      display: flex;
      margin-bottom: 15px;
      span {
        width: 30px;
        margin-right: 10px;
      }
    }
    .el-radio-group{
      margin-left: 40px;
    }
    .show_style{
      display: flex;
      flex-direction: column;
      .show_common {
        display: flex;
      }
      .show_top{
        margin-bottom: 15px;
      }
      .show_label{
        white-space: nowrap;
        margin-right: 10px;
      }
    }
    .is-active {
      pointer-events: none;
    }
  }
</style>
