<template>
  <div>
    <el-form
      ref="dataForm"
      :rules="rules"
      :model="ticketForm"
      status-icon
      label-position="right"
      label-width="120px"
    >
      <!-- <el-row>
        <el-col :span="12">
          <el-form-item label="工单编号" prop="ticketNo">
            <el-input v-model="ticketForm.ticketNo" size="mini" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工单状态" prop="ticketStatus">
            <el-input v-model="ticketForm.ticketStatus" size="mini" :disabled="true" />
          </el-form-item>
        </el-col>
      </el-row>-->
      <el-row>
        <el-col :span="12">
          <el-form-item label="工单类型" prop="ticketType">
            <el-radio-group v-model="ticketType" @change="handleTicketTypeChange">
              <el-radio :label="0">咨询</el-radio>
              <el-radio :label="1">投诉</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="ticketType==0">
        <el-col :span="24">
          <el-form-item label="咨询内容">
            <el-cascader
              v-model="consultValue"
              :options="ticketConsults"
              :props="{ expandTrigger: 'hover',value:'id',label:'name', multiple: true}"
              @change="cascaderChange"
              clearable
              :show-all-levels="false"
              size="mini"
            ></el-cascader>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="ticketType=='1'">
        <el-col :span="24">
          <el-form-item label="投诉内容" prop="ticketConsults">
            <el-cascader
              v-model="complainValue"
              :options="ticketComplains"
              :props="{ expandTrigger: 'hover',value:'id',label:'name', multiple: true}"
              @change="cascaderChange"
              clearable
              :show-all-levels="false"
              size="mini"
            ></el-cascader>

            <!-- <el-select v-model="ticketConsults" size="mini" multiple>
              <el-option v-for="type in defaultTypeOptions" :key="type.label" :label="type.value" :value="type.label" />
            </el-select>-->
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="工单等级" prop="等级">
            <el-select v-model="ticketForm.ticketLevel" size="mini">
              <el-option
                v-for="type in defaultLevelOptions"
                :key="type.label"
                :label="type.value"
                :value="type.label"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="服务时间" prop="serviceTime">
            <el-date-picker v-model="ticketForm.serviceTime" type="datetime" size="mini" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="ticketType=='1'">
        <el-col :span="24">
          <el-form-item label="投诉产品" prop="goodsId" class="product-item"> 
            <!-- <el-select v-model="ticketForm.goodsId" size="mini" >
               <el-option v-for="type in goodsList" :key="type.id" :label="type.name" :value="type.id" />
            </el-select>-->

            <el-cascader
              v-model="ticketForm.goodsId"
              :options="goodsList"
              :props="{ expandTrigger: 'hover',value:'id',label:'name',multiple: false}"
              @change="cascaderChange"
              clearable
              :show-all-levels="false"
               size="mini"
            ></el-cascader>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="ticketType=='1'">
        <el-col :span="12">
          <el-form-item label="投诉服务单" prop="orderId">
            <el-select v-model="ticketForm.orderId" size="mini" clearable>
              <el-option
                v-for="type in orderList"
                :key="type.bookOrderNo"
                :label="type.bookTime"
                :value="type.bookOrderNo"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="投诉服务者" prop="servicer">
            <el-input v-model="ticketForm.servicer" size="mini" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="事件描述" prop="ticketDes">
            <el-input v-model="ticketForm.ticketDes" size="mini" type="textarea" rows="4" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="特殊需求" prop="ticketSpecial">
            <el-input v-model="ticketForm.ticketSpecial" size="mini" type="text" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="本次处理内容" prop="memo">
            <el-input v-model="ticketForm.memo" size="mini" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-row>
        <el-col :span="24" v-if="ticketForm.ticketType==0">
          <el-form-item label="本次处理结果" prop="consultResult">
            <el-select v-model="ticketForm.consultResult" size="mini">
              <el-option
                v-for="type in consultResultList"
                :key="type.id"
                :label="type.name"
                :value="type.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" v-if="ticketForm.ticketType==1">
          <el-form-item label="本次处理结果" prop="complainResult">
            <el-select v-model="ticketForm.complainResult" size="mini">
              <el-option
                v-for="type in complainResultList"
                :key="type.id"
                :label="type.name"
                :value="type.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row> -->
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" size="mini" @click="showFinishDialog()">完成</el-button>
      <el-button type="danger" size="mini" @click="showAssign()">流转</el-button>
    </div>

   <el-dialog title="完成工单" :visible.sync="dialogFinishVisible" :modal="false"   width="600px"
      :close-on-click-modal="false"
      center>
       <el-form label-width="120px" style="width: 600px; margin-left:50px;">
    <el-form-item label="本次处理结果" prop="consultResult" class="result-input">
            <el-select v-model="handleResultValue" style="width:300px">
              <el-option
                v-for="type in handleResultList"
                :key="type.id"
                :label="type.name"
                :value="type.id"
              />
            </el-select>
          </el-form-item>
          </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="completedTicketM">完成</el-button>
        <el-button @click="wcgdVisible = false">取消</el-button>
      </span>
   
   </el-dialog>


    <!-- 流转 -->
    <el-dialog title="工单流转" :visible.sync="dialogAssignedVisible" :modal="false" center>
      <el-form
        ref="assignForm"
        :model="assignForm"
        :rules="assignRules"
        status-icon
        label-position="left"
        label-width="150px"
        style="width: 600px; margin-left:50px;"
      >
        <el-form-item label="分配到技能组" prop="assignedSkillGroup">
          <el-select v-model="assignForm.assignedSkillGroup" style="width:300px">
            <el-option
              v-for="item in skillGroups"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAssignedVisible = false">取消</el-button>
        <el-button type="primary" @click="updateAssigned">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { read } from "@/api/customer";
import { allChannel } from "@/api/channel";
import { allSkillGroup } from "@/api/campaign";
import { addRelation } from "@/api/cti";
import panelApi from "@/api/panel";
const defaultTypeMap = [
  { label: "0", value: "咨询" },
  { label: "1", value: "投诉" }
];

const defaultCityMap = [
  { label: "1", value: "上海" },
  { label: "2", value: "北京" },
  { label: "3", value: "深圳" },
  { label: "4", value: "南京" }
];

const defaultLevelMap = [
  { label: 0, value: "无" },
  { label: 1, value: "一般" },
  { label: 2, value: "严重" },
  { label: 3, value: "非常严重" }
];

export default {
  name: "CustomerEdit",
  filters: {},
  data() {
    return {
      consultValue: [],
      complainValue: [],
      // productValue: [],
      goodsList: [], //产品列表
      orderList: [], //服务单列表
      consultResultList: [],
      complainResultList: [],
      channels: [],
      skillGroups: [],
      handleResultList:[],
      handleResultValue:"",
      dialogFinishVisible:false,//完成
      dialogAssignedVisible: false, //流转
      defaultTypeOptions: Object.assign({}, defaultTypeMap),
      defaultLevelOptions: Object.assign({}, defaultLevelMap),
      disabledTel: true,
      ticketConsults: [], // 咨询类型
      ticketComplains: [], // 投诉类型
      ticketAction: {
        memo: undefined
      },
      // ticketType: 0, 
      ticketForm: {
        ticketNo: undefined,
        ticketType: 0, //0咨询 1投诉
        ticketLevel: 0,
        serviceTime: "",
        ticketSpecial: "",
        ticketDes: "",
        goodsId: [],
        consultResult: "",
        complainResult: "",
        servicer: "",
        orderId: ""
      },
      assignForm: {
        assignedSkillGroup: ""
      },
      assignRules: {
        assignedSkillGroup: [
          { required: true, message: "分配到技能组不能为空", trigger: "blur" }
        ]
      },
      rules: {
        ticketDes: [
          { required: true, message: "工单事件描述不能为空", trigger: "blur" }
        ],
        // ticketConsults: [{ required: true, message: '咨询内容不能为空', trigger: 'blur' }],
        memo: [
          { required: true, message: "本次处理内容不能为空", trigger: "blur" }
        ],
        consultResult: [
          { required: true, message: "本次处理结果不能为空", trigger: "blur" }
        ],
        complainResult: [
          { required: true, message: "本次处理结果不能为空", trigger: "blur" }
        ],
        ticketType: [
          { required: true, message: "工单类型不能为空", trigger: "blur" }
        ],
        tel: [
          { required: true, message: "客户联系方式不能为空", trigger: "blur" }
        ]
      }
    };
  },
  watch: {},
  computed: {
  ticketType : {
    
      get() {
        return this.$store.state.panel.ticketType;
      },
      set(value){
        this.$store.state.panel.ticketType=value;
      }
    },
  },
  created() {
    // allChannel().then(res => {
    //   this.channels = res.data.data
    // })
    this.getTicketConsult();
    this.getGoodsList();
    this.getTicketResultList();

    console.info("callid");
    console.info(this.$store.state.panel.callId);
  },
  methods: {
    getTicketConsult() {
      panelApi
        .ticketConsultList()
        .then(res => {
          console.log(res.data);
          let list = res.data.data.list;
          console.log(list);
          this.ticketConsults = list.filter(item => {
            return item.type == 0;
          });
          this.ticketComplains = list.filter(item => {
            return item.type == 1;
          });
        })
        .catch(error => {
          console.log(error);
        });
    },
    getGoodsList() {
      panelApi
        .goodsList()
        .then(res => {
          //console.log(res.data);
          this.goodsList = res.data.data;
        })
        .catch(error => {
          console.log(error);
        });
    },
    getTicketResultList() {
      panelApi
        .ticketResult()
        .then(res => {
          //console.log(res.data);
          this.consultResultList = res.data.data.filter(item => {
            return item.type == 0;
          });
          this.complainResultList = res.data.data.filter(item => {
            return item.type == 1;
          });
        })
        .catch(error => {
          console.log(error);
        });
    },
    getServiceList() {
      let params = { customerId: this.$store.state.panel.customerId };
      panelApi
        .serviceList(params)
        .then(res => {
          console.log(res.data);
          this.orderList = res.data.data;
        })
        .catch(error => {
          console.log(error);
        });
    },
    cascaderChange(value) {
      console.log(value);
    },
    createTicket(status, substatus) {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          let consults = [];
          let goodsId = "";
          if (this.ticketType == 1) {
            this.complainValue.forEach(item => {
              consults.push({ consultId: item[2] });
            });

            goodsId =
              this.ticketForm.goodsId.length >= 1
                ? this.ticketForm.goodsId[1]
                : "";
          } else {
            this.consultValue.forEach(item => {
              consults.push({ consultId: item[2] });
            });
            goodsId = "";
          }

          // let result =
          //   this.ticketForm.ticketType == 1
          //     ? this.ticketForm.complainResult
          //     : this.ticketForm.consultResult;
          let params = {
            action: {
              memo: this.ticketForm.memo, //处理内容
              // result: result //结果
            },
            consults: consults,
            ticket: {
              status: status,
              customerId: this.$store.state.panel.user.id,
              substatus: substatus,
              ticketType: this.ticketType,
              ticketLevel: this.ticketForm.ticketLevel,
              serviceTime: this.formateDate(this.ticketForm.serviceTime),
              ticketDes: this.ticketForm.ticketDes,
              ticketSpecial: this.ticketForm.ticketSpecial,
              goodsId: goodsId,
              servicer:
                this.ticketType == 1 ? this.ticketForm.servicer : "",
              orderId:
                this.ticketType == 1 ? this.ticketForm.orderId : ""
            }
          };
          if (substatus == 102) {
            params.action.skillGroupId = this.assignForm.assignedSkillGroup;
            params.ticket.skillGroupId = this.assignForm.assignedSkillGroup;
          }
          if(status==2){
            params.action.result=this.handleResultValue;
          }
          console.log(params);
          panelApi
            .ticketCreate(params)
            .then(res => {
              console.log(res.data);
              if (res.data.errno == "0") {
                this.dialogFinishVisible = false;
                this.dialogAssignedVisible = false;
                this.$message.success("提交成功");
                this.consultValue = [];
                this.complainValue = [];
                this.ticketType=0;
                this.ticketForm = {
                  ticketType: 0, //0咨询 1投诉
                  ticketLevel: 0,
                  serviceTime: "",
                  ticketSpecial: undefined,
                  ticketDes: undefined,
                  goodsId: [],
                  consultResult: "",
                  complainResult: "",
                  servicer: "",
                  orderId: ""
                };
                this.assignForm = { assignedSkillGroup: "" };
                //  更新客户信息
                this.$store.dispatch("CUSTOMER_DETAIL", {
                  id: this.$store.state.panel.user.id
                });

                //this.$store.state.panel.callId>0 表示从电访记录列表调出的此界面 需要保存ticket与calllog关系
                if (
                  this.$store.state.panel.callId != null &&
                  this.$store.state.panel.callId > 0
                ) {
                  var data = {
                    ticketId: res.data.data,
                    type: 0,
                    fId: this.$store.state.panel.callId,
                    deleted: false
                  };
                  addRelation(data);
                }
              } else {
                this.$message.error(res.data.errmsg);
              }
            })
            .catch(error => {
              console.log(error);
              this.$message.error(error.data.errmsg);
            });
        }
      });
    },
    upgradeTicket() {},
    editCustomerDia(row) {
      this.userForm = row;
      this.dialogFormVisible = true;

      if (!row.tel) {
        this.disabledTel = true;
      }

      read(row.id).then(res => {
        this.userForm = res.data.data.data.user;
        this.fns = res.data.data.data.fns;
        // console.info(this.userForm)
      });
    },

    handleTicketTypeChange(value) {
      // 咨询类型变更
      console.log(value);
      if (value == "1") {
        this.ticketForm.orderId = "";
        this.getServiceList();
      }
    },
    showFinishDialog(){
      // createTicket(2,201)
       this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.handleResultList=(this.ticketType == 1?this.complainResultList:this.consultResultList);
          this.handleResultValue='';
          this.dialogFinishVisible = true;
        }
      });
    },
    completedTicketM() {
       if(this.handleResultValue==''){
 this.$message.error("本次处理结果不能为空");
        return;
      }else{
        this.createTicket(2,201);
      }
    },
    showAssign() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if (this.skillGroups.length == 0) {
            allSkillGroup().then(res => {
              this.skillGroups = res.data.data;
            });
          }

          this.dialogAssignedVisible = true;
        }
      });
    },
    updateAssigned() {
      this.$refs["assignForm"].validate(valid => {
        if (valid) {
          this.createTicket(1, 102);
        }
      });
    }
  }
};
</script>

<style>
.el-table th.gutter {
  display: table-cell !important;
}
.dialog-footer {
  padding: 20px;
  padding-top: 10px;
  text-align: right;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}
.el-input-group__append {
  padding: 0 10px;
  cursor: pointer;
}
.product-item div.el-cascader--mini {
  width: 100%;
}
.el-date-editor.el-input{
  /* width:auto; */
}
</style>
