<template>
  <div class="order-draft">
    <div>
      <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
        <el-form-item label="草稿名称">
          <el-input v-model.trim="formInline.name" clearable placeholder="请输入草稿名称"></el-input>
        </el-form-item>
        <el-form-item label="发起时间">
          <el-date-picker v-model="formInline.addTime" clearable format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" range-separator="至"
                          start-placeholder="开始时间"
                          end-placeholder="结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="onSubmit">搜索</el-button>
          <el-button @click="resetClick">刷新</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-table :loading="loading" border :data="dataList" style="width: 100%">
        <el-table-column align="center" prop="id" label="草稿编号"></el-table-column>
        <el-table-column align="center" prop="draftType" label="草稿类型">
          <template slot-scope="scope">
            {{scope.row.draftType ? scope.row.draftType === 4 ? '订购同步' : '流量数据同步' : ''}}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="draftName" label="草稿名称"></el-table-column>
        <el-table-column align="center" prop="createUser" label="发起人"></el-table-column>
        <el-table-column align="center" prop="createTime" label="发起时间"></el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="addClick(scope.row)">修改</el-button>
            <el-button type="text" size="small" @click="deleteClick(scope.row)" >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: right;margin-top: 10px">
        <el-pagination background @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page="page"
                       :page-sizes="[10, 20, 30, 50]"
                       :page-size="limit"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="total"></el-pagination>
      </div>
      <el-dialog :title="addTittle" :visible.sync="dialogVisible" width="60%" @close="$refs.addFrom.clearValidate()">
        <el-form  ref="addFrom" :rules="rules" label-position="left" label-width="110px"  :model="addform" class="order-add-form" size="small">
          <el-form-item label="CPID" prop="flowcp">
            <el-input v-model.trim="addform.flowcp" clearable placeholder="请输入CPID"></el-input>
          </el-form-item>
          <el-form-item label="配置名称" prop="flowcpName">
            <el-input  v-model.trim="addform.flowcpName" clearable placeholder="请输入配置名称"></el-input>
          </el-form-item>
          <el-form-item label="类型" prop="mobType">
            <el-select v-model="addform.mobType" clearable placeholder="请选择类型">
              <el-option label="0" value="0"></el-option>
              <el-option label="1" value="1"></el-option>
            </el-select>
          </el-form-item>
          <p>类型备注：1 不返回号码给合作方（代码中体现是手机号会多一层加密）；0 返回手机号给合作方（只加密一次）</p>
          <el-form-item label="同步接口链接" prop="alertUrl" class="addform-teaxt">
            <el-input v-model.trim="addform.alertUrl" clearable placeholder="请输入同步接口链接"></el-input>
          </el-form-item>
          <el-form-item class="addform-sub">
            <el-button @click="setdraftClick">保存草稿</el-button>
            <el-button type="primary" @click="setSubmitClick">提交审核</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <el-dialog :title="addTittle" :visible.sync="dialogVisible1" width="60%" @close="$refs.addFrom.clearValidate()">
        <el-form ref="addFrom" :rules="rulesd" label-position="left" label-width="110px"  :model="addform" class="order-add-form" size="small">
          <el-form-item label="CPID" prop="cpid">
            <el-input v-model.trim="addform.cpid" clearable placeholder="请输入CPID"></el-input>
          </el-form-item>
          <el-form-item label="配置名称" prop="name">
            <el-input  v-model.trim="addform.name" clearable placeholder="请输入配置名称"></el-input>
          </el-form-item>
          <el-form-item label="同步接口链接" prop="url" class="addform-teaxt">
            <el-input v-model.trim="addform.url" clearable placeholder="请输入同步接口链接"></el-input>
          </el-form-item>
          <el-form-item label="定时任务描述" prop="description" class="addform-teaxt">
            <el-input type="textarea"  v-model.trim="addform.description" clearable placeholder="请输入定时任务描述"></el-input>
          </el-form-item>
          <el-form-item class="addform-sub">
            <el-button @click="setdraftClick">保存草稿</el-button>
            <el-button type="primary" @click="setSubmitClick">提交审核</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <AddBox v-if="addVisible" ref="addBox" :addTitle="addBoxTitle" @setFlow="addBoxClick" />
    </div>
  </div>
</template>

<script>
import { post, get } from "@/api/common";
import AddBox from "@/components/flowOderAdd/addBox";
export default {
  name: "draftSynchronous",
  components:{AddBox},
  data(){
    return{
      page:1,
      limit:10,
      total:10,
      formInline:{
        name:'',
        addTime:'',
        draftTypes:'3,4'
      },
      dataList:[],
      loading:false,
      dialogVisible:false,
      dialogVisible1:false,
      addVisible:false,
      addTittle:'配置产品转接',
      addBoxTitle:'请选择产品转接审核模板',
      addform: {
        id:'',
        flowcpName:'', //	名称
        flowcp:'', //cpid
        status:0,//状态
        mobType: '1',//类型
        alertUrl: '',//同步接口链接
        name:'', //	名称
        cpid:'', //cpid
        url: '',//同步接口链接
        description: '',//定时任务描述
        auditVersion:0, //版本
        auditSource:'', //版本
        auditStatus:0, //审核状态
      },
      prevform:{},
      rules:{
        flowcp: [
          { required: true, message: '请输入CPID', trigger: 'blur' },
        ],
        flowcpName: [
          { required: true, message: '请输入配置名称', trigger: 'blur' },
        ],
        mobType: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        alertUrl: [
          { required: true, message: '请输入同步接口链接', trigger: 'blur' },
        ],
      },
      rulesd:{
        cpid: [
          { required: true, message: '请输入CPID', trigger: 'blur' },
        ],
        name: [
          { required: true, message: '请输入配置名称', trigger: 'blur' },
        ],
        url: [
          { required: true, message: '请输入同步接口链接', trigger: 'blur' },
        ],
        description: [
          { required: true, message: '请输入定时任务描述', trigger: 'blur' },
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods:{
    onSubmit(){
      this.getList()
    },
    resetClick(){
      this.formInline = {
        name:'',
        addTime:'',
        draftTypes:'3,4',
      }
      this.page = 1
      this.limit = 10
      this.getList()
    },
    getList(){
      this.loading = true
      let { name,addTime,draftTypes} = this.formInline
      if(!addTime){
        addTime = []
      }
      get("/manager/draft/list", {
        name,draftTypes,
        startTime:addTime.length ? addTime[0] : null,
        endTime:addTime.length ? addTime[1] : null,
        pageSize: this.limit,
        pageNum: this.page,
      }).then((res) => {
        this.dataList = res.data.records
        this.total = res.data.total;
        this.limit = res.data.size;
        this.page = res.data.current;
        this.loading = false
      });
    },
    //切换当前页条数
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.limit = val
      this.getList()
    },
    //切换页数
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.page = val
      this.getList()
    },
    //编辑
    addClick(row){
      if (row.draftType){
        //产品转接
        if (row.draftType === 3){
          this.addTittle = '编辑流量同步参数'
          this.addBoxTitle = '请选择流量同步审核模板'
          let JsonData = JSON.parse(row.json)
          this.eidtFlowData(JsonData,row)
        }else if (row.draftType === 4){
          this.addTittle = '编辑订购同步参数'
          this.addBoxTitle = '请选择订购同步审核模板'
          let JsonData = JSON.parse(row.json)
          this.eidtChannelData(JsonData,row)
        }
      }else {
        this.$message.error('无效草稿信息');
      }
    },
    //编辑流量同步回显
    eidtFlowData(data,row){
      let {flowcpName,flowcp,status,mobType,alertUrl,auditVersion,auditStatus,auditSource,auditTemplateId} = data
      let {id} = row
      this.addform = {flowcpName,flowcp,status,mobType,alertUrl,id,dataId:data.id,draftType:3,
        auditVersion:auditVersion ? auditVersion : 0,
        auditSource,auditStatus,
        auditTemplateId:auditTemplateId ? auditTemplateId : null}
      this.prevform = JSON.stringify(this.addform)
      this.dialogVisible = true
    },
    //编辑订购同步回显
    eidtChannelData(data,row){
      let {name,cpid,status,url,smsSend,description,auditVersion,auditStatus,auditSource,auditTemplateId} = data
      let {id} = row
      this.addform = {name,cpid,status,url,smsSend,description,id,dataId:data.id,draftType:4,
        auditVersion:auditVersion ? auditVersion : 0,
        auditSource,auditStatus,
        auditTemplateId:auditTemplateId ? auditTemplateId : null}
      this.prevform = JSON.stringify(this.addform)
      this.dialogVisible1 = true
    },
    //保存草稿
    setdraftClick(){
      let { draftType} = this.addform
      if (draftType === 3){
        this.setdraftFlow()
      }else if (draftType === 4){
        this.setdraftOrder()
      }
    },
    //保存流量同步草稿
    setdraftFlow(){
      let { flowcpName,flowcp,status,mobType,alertUrl,draftType,id} = this.addform
      let JSONData = { flowcpName,flowcp,status,mobType,alertUrl}
      let parms = { cpid:flowcp,json:JSON.stringify(JSONData),draftType,id}
      this.$refs['addFrom'].validate((valid) => {
        if (valid){
          if (JSON.stringify(this.addform) !== this.prevform){
            post("/manager/draft/submit", parms).then((res) => {
            if (res.code === 10000) {
              this.$message.success(res.message);
              this.dialogVisible = false
              this.getList()
            }
          });
          }else {
            this.$message.warning('未修改内容 请修改内容后重试');
            return false;
          }
        }else {
          this.$message.warning('请完善信息');
          return false;
        }
      })
    },
    //保存订购同步草稿
    setdraftOrder(){
      let { name,cpid,status,url,smsSend,description,id,draftType} = this.addform
      let JSONData = { name,cpid,status,url,smsSend,description,id,}
      let parms = { cpid,json:JSON.stringify(JSONData),draftType,id}
      this.$refs['addFrom'].validate((valid) => {
        if (valid){
          if (JSON.stringify(this.addform) !== this.prevform){
            post("/manager/draft/submit", parms).then((res) => {
              if (res.code === 10000) {
                this.$message.success(res.message);
                this.dialogVisible1 = false
                this.getList()
              }
            });
          }else {
            this.$message.warning('未修改内容 请修改内容后重试');
            return false;
          }
        }else {
          this.$message.warning('请完善信息');
          return false;
        }
      })
    },
    setSubmitClick(){
      let { draftType,auditTemplateId} = this.addform
      this.addVisible = true
      if (draftType === 3){
        this.$nextTick(() => {
          this.$refs.addBox.getTemplate(auditTemplateId)
        })
      }else if (draftType === 4){
        this.$nextTick(() => {
          this.$refs.addBox.getTemplate(auditTemplateId)
        })
      }
    },
    addBoxClick(data){
      let { draftType} = this.addform
      if (draftType === 3){
        this.setSubmitFlow(data)
      }else if (draftType === 4){
        for (let i = 0; i< 3;i++) {
          this.setSubmitOrder(i, data)
        }
      }
    },
    //  提交审核
    setSubmitFlow(data){
      let { flowcpName,flowcp,status,mobType,alertUrl,id,dataId,auditVersion,auditSource,auditStatus} = this.addform
      let JSONData = { flowcpName,flowcp,status,mobType,alertUrl,draftId:id,id:dataId,
        auditVersion:id ? auditVersion + 1 : auditVersion,
        auditSource,auditStatus,...data }
      let parms = JSON.stringify(JSONData)
      this.$refs['addFrom'].validate((valid) => {
        if (valid){
          post("/partner-sync/flow/submit", parms).then((res) => {
            if (res.code === 10000) {
              this.$message.success(res.message);
              this.dialogVisible = false
              this.addVisible = false
              this.$refs.addBox.dialogVisible = false
              this.getList()
            }
          });
        }else {
          this.$message.warning('请完善信息');
          return false;
        }
      })
    },
    //  提交审核
    setSubmitOrder(i,data){
      let { name,cpid,status,url,smsSend,description,id,dataId,auditVersion,auditSource,auditStatus} = this.addform
      let JSONData = { name,cpid,status,url,smsSend,description,draftId:id,id:dataId,
        auditVersion:id ? auditVersion + 1 : auditVersion,
        auditSource,auditStatus,dealType:i,...data }
      let parms = JSON.stringify(JSONData)
      this.$refs['addFrom'].validate((valid) => {
        if (valid){
          post("/partner-sync/order/submit", parms).then((res) => {
            if (i === 2 && res.code === 10000) {
              this.$message.success(res.message);
              this.dialogVisible1 = false
              this.addVisible = false
              this.$refs.addBox.dialogVisible = false
              this.getList()
            }
          });
        }else {
          this.$message.warning('请完善信息');
          return false;
        }
      })
    },
    //  删除
    deleteClick(row){
      this.$confirm('是否删除草稿箱内容，删除后无法恢复？', '确认信息')
        .then(_ => {
          get("/manager/draft/delete", {
            id:row.id,
          }).then((res) => {
            this.$message.success(res.message);
            this.getList()
          });
        }).catch(_ => {});
    },
  }
}
</script>

<style lang="scss" scoped>
.order-draft{
  padding: 20px !important;
  .order-add-form{
    display: flex;
    flex-wrap: wrap;
    .el-form-item{
      width: 50%;
      .el-input{
        width: 80%;
      }
      .el-textarea{
        width: 80%;
      }
    }
    .addform-teaxt{
      width: 100%;
    }
    .addform-sub{
      width: 100%;
      text-align: center;
      ::v-deep .el-form-item__content{
        margin-left: 0 !important;
      }
      .el-button+.el-button{
        margin-left: 100px;
      }
    }
  }
}
</style>
