<template>
    <div class="app-container">
      <van-nav-bar
        :title="(operationIntent == 3 ? '添加' : '') + '纠纷调解'"
        left-arrow
        fixed
        placeholder
        @click-left="goBack()"
        z-index="998"
      >
        <template #right>
          <van-icon name="../../../static/images/icon/icon_flow.png" size="20" @click="openMenu" v-if="!!id"/>
        </template>
      </van-nav-bar>

      <div class="main" style="padding-bottom: 1rem;">
        <van-form ref="form">
          <div :class="allowCUD && formEnabled.baseFormEnabled ? '' : 'noModify'">
<!--            <p class="topTit">纠纷调解</p>-->
            <template> <!-- 申请 基本信息 -->
              <div>
                <p class="main_title">基本信息</p>
                <div class="main_box">
                  <van-field :readonly="true" v-model="arbitrationData.applicant" label="申请人" placeholder="申请人" input-align="right" required :rules="[{ required: true }]"/>
                  <van-field required :readonly="true" v-model="arbitrationData.applicantPhone" label="联系电话" placeholder="联系电话" input-align="right" type="digit" :rules="[{pattern: /(^\d{7}(\d{4})?$)/}]"/>
                  <field-select
                    v-model="arbitrationData.applyProposerId"
                    label="宅基地申请"
                    value-key="projectName"
                    data-key="id"
                    placeholder="选择宅基地申请"
                    :rules="[{ required: true }]"
                    required
                    :readonly="!allowCUD || !formEnabled.baseFormEnabled"
                    :columns="userHouseApplyProposer"
                  />
                  <van-field :readonly="!allowCUD || !formEnabled.baseFormEnabled" v-model="arbitrationData.disputant" label="纠纷人" placeholder="纠纷人" input-align="right" required :rules="[{ required: true }]"/>
                  <field-date-picker
                    v-model="arbitrationData.applyTime"
                    label="申请时间"
                    placeholder="请选择申请时间"
                    :rules="[{ required: true }]"
                    formatter="yyyy-MM-dd"
                    required
                    :readonly="!allowCUD || !formEnabled.baseFormEnabled"
                  />
                </div>
              </div>

              <div>
                <p class="main_title"><span style="color: red;">*</span>纠纷事项</p>
                <div class="main_box">
                  <van-field
                    rows="3"
                    autosize
                    type="textarea"
                    placeholder="纠纷事项"
                    input-align="left"
                    v-model="arbitrationData.disputes"
                    :readonly="!allowCUD || !formEnabled.baseFormEnabled"
                    :rules="[{ required: true }]"
                  />
                </div>
              </div>

              <div>
                <p class="main_title">备注说明</p>
                <div class="main_box">
                  <van-field
                    rows="3"
                    autosize
                    type="textarea"
                    placeholder="备注说明"
                    input-align="left"
                    v-model="arbitrationData.remark"
                    :readonly="!allowCUD || !formEnabled.baseFormEnabled"
                  />
                </div>
              </div>
            </template>
          </div>

        </van-form>
      </div>

      <!-- 底部按钮 -->
      <van-goods-action style="z-index: 999;" v-if="allowCUD && (formVisible.editVisible || formVisible.operationVisible || formVisible.approvalVisible)">
        <template v-if="formVisible.editVisible">
          <van-goods-action-button type="info" text="保存"  @click="onSubmit('add')" :disabled="!formEnabled.baseFormEnabled" v-if="formEnabled.baseFormEnabled"/>
          <van-goods-action-button type="info" text="提交"  @click="onSubmit(formEnabled.baseFormEnabled ? 'save_and_submit' : 'submit')" v-if="formEnabled.submitEnabled"/>
        </template>
        <template v-if="formVisible.approvalVisible">
          <van-goods-action-button type="info" text="受理"  @click="onSubmit('agree')" :disabled="!formEnabled.approvalEnabled"/>
          <van-goods-action-button type="danger" text="驳回"  @click="onSubmit('reject')" v-if="formEnabled.rejectEnabled"/>
        </template>
        <template v-if="formVisible.operationVisible">
          <van-goods-action-button type="info" text="调解"  @click="onSubmit('mediate')" v-if="formEnabled.mediateEnabled"/>
          <van-goods-action-button type="danger" text="仲裁"  @click="onSubmit('arbitrate')" v-if="formEnabled.arbitrateEnabled"/>
          <van-goods-action-button type="info" text="归档"  @click="onSubmit('archive')" v-if="formEnabled.archiveEnabled"/>
        </template>
      </van-goods-action>

      <van-action-sheet v-model="menuVisible" :actions="menuActions" @select="onActionSelect"
                        cancel-text="取消"
                        title="详细信息"
                        close-on-click-action>
      </van-action-sheet>
    </div>
</template>

<script>

import FieldSelect from "@/components/form/FieldSelect";
import FieldDatePicker from "@/components/form/FieldDatePicker";
import {formatDate} from "element-ui/src/utils/date-util.js";
import {getInfo} from '@/api/login/index'
import {Notify} from "vant";
import { getList } from "@/api/onlineHome/homestead/application";
import { addArbitration, getArbitrationDetail, submitArbitration, editArbitration } from "@/api/onlineHome/homestead/arbitration";

// 意图
const INTENT_VIEW = 1;
const INTENT_EDIT = 2;
const INTENT_ADD = 3;

export default {
  name: "ArbitrationDetail",
    components: {
      FieldDatePicker, FieldSelect},
    data() {
    return {
      // 申请ID
      id: '',
      // 表单数据
      arbitrationData: {
        applicantPhone: '',
        applyProposerId: '',
        applicant: '',
        disputant: '',
        disputes: '',
        remark: '',
        applyTime: '',
        deptName: '',
        disputeStatus: '1',
      },
      // 表单意图
      operationIntent: INTENT_ADD,
      // 显示控制
      formVisible: {
        editVisible: false,
        approvalVisible: false,
        operationVisible: false,
        finishVisible: false,
      },
      // 表单启用控制
      formEnabled: {
        baseFormEnabled: false,
        submitEnabled: false,
        approvalEnabled: false,
        rejectEnabled: false,
        mediateEnabled: false,
        arbitrateEnabled: false,
        archiveEnabled: false,
      },
      currentUserRole: null,
      userHouseApplyProposer: [],
      menuVisible: false,
      menuActions: [
        {name: '调解/冲裁员', route: {name:'arbitrationHandlerList', query: {}}},
        {name: '处理过程', route: {name:'arbitrationProcessList', query: {}}},
      ]
    };
  },
  created() {
    this.id = this.$route.query.id;
    this.type = this.$route.query.type;
    this.getFormIntent();
    this.getDetail();
    this.getUserHouseApplyProposer();
  },
  computed: {
    allowCUD: function () {
      return this.$store.getters.businessLevel == '2' || true
    },
  },
  methods: {
    getDetail(){
      this.reset();
      if(this.id)
      {
        getArbitrationDetail(this.id).then(response => {
          this.init(response.data);
        });
      }
      else
      {
        this.init();
        this.getApplyerDetail();
      }
    },
    // 全局初始化
    init(value) {
      const role = this.$store.getters.roles;
      this.currentUserRole = role[0];

      // 默认状态
      this.formVisible.editVisible = false;
      this.formVisible.approvalVisible = false;
      this.formVisible.operationVisible = false;

      this.formEnabled.baseFormEnabled = false;
      this.formEnabled.submitEnabled = false;
      this.formEnabled.approvalEnabled = false;
      this.formEnabled.rejectEnabled = false;
      this.formEnabled.mediateEnabled = false;
      this.formEnabled.arbitrateEnabled = false;
      this.formEnabled.archiveEnabled = false;

      switch (this.operationIntent) {
        // 查看
        case INTENT_VIEW:
          this.arbitrationData = value;
          switch(value.disputeStatus)
          {
            case '1': // 草稿
              this.formEnabled.submitEnabled = true;
              this.formVisible.editVisible = true;
              break;
            case '2': // 待审
              this.formVisible.approvalVisible = true;
              this.formEnabled.approvalEnabled = true;
              this.formEnabled.rejectEnabled = true;
              break;
            case '3': // 受理
              this.formVisible.operationVisible = true;
              this.formEnabled.mediateEnabled = true;
              this.formEnabled.arbitrateEnabled = true;
              break;
            case '4': // 驳回
              this.formVisible.approvalVisible = true;
              this.formEnabled.approvalEnabled = true;
              break;
            case '5': // 调解
              this.formVisible.operationVisible = true;
              this.formEnabled.arbitrateEnabled = true;
              this.formEnabled.archiveEnabled = true;
              break;
            case '6': // 仲裁
              this.formVisible.operationVisible = true;
              this.formEnabled.archiveEnabled = true;
              break;
            case '7': // 归档
              break;
            default:
              break;
          }
          break;

        // 编辑/审批
        case INTENT_EDIT:
          this.arbitrationData = value;
          this.formEnabled.baseFormEnabled = true;
          this.formVisible.editVisible = true;
          this.formEnabled.submitEnabled = true;
          break;

        // 新建
        case INTENT_ADD:
          this.formEnabled.baseFormEnabled = true;
          this.formVisible.editVisible = true;
          this.formEnabled.submitEnabled = true;
          break;
      }
    },
    // 获取query的意图
    getFormIntent() {
      console.log(this.type);
      switch (this.type) {
        case 'done':
        case 'view':
          this.operationIntent = INTENT_VIEW;
          break;
        case 'modify':
        case 'audit':
        case 'todo':
          this.operationIntent = INTENT_EDIT;
          break;
        case 'add':
        default:
          this.operationIntent = INTENT_ADD;
          break;
      }
      return this.operationIntent;
    },
    // 获取日期, yyyy-MM-dd
    getDate(d) {
      return formatDate(d ? d : new Date(), 'yyyy-MM-dd');
    },
    // 初始化基础表单
    reset() {
      this.$set(this.arbitrationData, 'applicantPhone', '');
      this.$set(this.arbitrationData, 'applyProposerId', '');
      this.$set(this.arbitrationData, 'applicant', '');
      this.$set(this.arbitrationData, 'disputant', '');
      this.$set(this.arbitrationData, 'disputes', '');
      this.$set(this.arbitrationData, 'remark', '');
      this.$set(this.arbitrationData, 'deptName', '');
      this.$set(this.arbitrationData, 'disputeStatus', 1);
      this.$set(this.arbitrationData, 'applyTime', this.getDate());
    },
    //返回上一步操作
    goBack(){
      this.$router.push({name: this.$router.back(-1)});
    },
    // 全局提交
    onSubmit(intent){
      console.log(this.arbitrationData, intent);
      switch (intent) {
        case 'add':
        case 'modify':
          this.saveArbitration();
          break;
        case 'submit':
          this.submitArbitration();
          break;
        case 'save_and_submit':
          this.saveArbitration(true);
          break;
        case 'agree':
          this.agreeArbitration();
          break;
        case 'reject':
          this.rejectArbitration();
          break;
        case 'mediate':
          this.mediateArbitration();
          break;
        case 'arbitrate':
          this.arbitrateArbitration();
          break;
        case 'archive':
          this.archiveArbitration();
          break;
        default:
          console.error('Unknown intent! ', intent);
          break;
      }
    },
    // 获取申请人信息
    getApplyerDetail(){
      getInfo().then(res => {
        let user = res.user;
        console.log(user);
        this.$set(this.arbitrationData, 'applicantPhone', user.phonenumber);
        this.$set(this.arbitrationData, 'applicant', user.nickName);
      });
    },
    // 检查字符串, 不符合返回true
    checkString(value, regexp) {
      let res = value === undefined || value === null || value === '' || value.toString().trim().length === 0;
      if(res)
        return true;
      if(regexp)
        res = !value.match(regexp);
      return res;
    },
    // 保存申请(是否提交)
    saveArbitration(submit) {
      this.$refs.form.validate().then(() => {
        /*if(this.checkString(this.arbitrationData.tHouseApplyProposedSituation.theGeom))
        {
          this.notify("请标注宅基地位置!", 'danger');
          return;
        }*/
        console.log("进行保存", this.arbitrationData);
        (this.arbitrationData.id ? editArbitration : addArbitration)(this.arbitrationData).then((response) => {
          if(submit)
          {
            if(!this.arbitrationData.id)
              this.arbitrationData.id = response.data;
            this.submitArbitration();
          }
          else
          {
            this.notify("保存成功", 'success');
            this.goBack();
          }
        }).catch((e) => {
          this.notify("保存失败!", 'danger');
        }).finally(() => {
        });
      }).catch(e => {
        this.notify('请填写完整表单', 'danger');
        return;
      });
    },
    submitArbitration() {
      this.setArbitrationStatus('2', '提交');
    },
    agreeArbitration() {
      this.setArbitrationStatus('3', '受理');
    },
    rejectArbitration() {
      this.setArbitrationStatus('4', '驳回');
    },
    mediateArbitration() {
      this.setArbitrationStatus('5', '调解');
    },
    arbitrateArbitration() {
      this.setArbitrationStatus('6', '仲裁');
    },
    archiveArbitration() {
      this.setArbitrationStatus('7', '归档');
    },
    setArbitrationStatus(status, reason) {
      submitArbitration(this.arbitrationData.id, status).then((response) => {
        this.notify(`${reason}成功`, 'success');
        this.goBack();
      }).catch((e) => {
        this.notify(`${reason}成功失败!`, 'danger');
      }).finally(() => {
      });
    },
    // 请求结果提示工具函数
    notify(message, type) {
      Notify.clear();
      Notify({ type: type || 'primary', message: message });
    },
    getUserHouseApplyProposer()
    {
      getList().then((resp) => {
        this.userHouseApplyProposer = resp.rows;
      });
    },
    openMenu() {
      this.menuVisible = true;
    },
    onActionSelect(a, index) {
      a.route.query.arbitrationId = this.arbitrationData.id;
      this.$router.push(a.route);
    },
  },
  watch: {
  }
}
</script>

<style scoped lang="scss">
  .app-container {
    padding-bottom: 5%;
  }
  .examine_box{
    background-color: #1D6FE9!important;
    padding: 0.18rem!important;
    padding-left: 0!important;
    border-radius: 0.15rem!important;
    margin-top: 0.3rem!important;
  }
  .examine_box .van-col:first-child{
    color: #FFF!important;
    font-size: 0.45rem!important;
    text-align: center!important;
  }
  .examine_box .van-col:last-child{
    background-color: #FFF!important;
    border-radius: 0.15rem!important;
    overflow: hidden!important;
    .van-radio-group--horizontal{
      padding: 0.2rem 0;
      border-bottom: 1px solid #eee;
    }
  }
  #mapWrap{
    width: 96%;
    margin: 0 auto;
    border-bottom-left-radius: 12px;
    border-bottom-right-radius: 12px;
    overflow: hidden;
  }
  .mapBox{
    position: relative;
    .mapBox_button{
      position: absolute;
      top: 0.2rem;
      right: 2%;
    }
  }
  .van-steps{
    padding: 2% 6% 0;
  }
  .topTit{
    font-size: 0.45rem;
    background-color: #1D6FE9;
    color: #FFFFFF;
    line-height: 58px;
    text-align: center;
    padding: 15px 0;
    box-shadow: 0px 3px 6px 0px rgba(15,67,145,0.40);
  }
  .main_title{
    font-size: 0.4rem;
    color: #1D6FE9;
    margin: 0.2rem 6%;
    position: relative;
  }
  .main_box{
    width: 96%;
    margin: 0 auto;
    border-radius: 6px;
    box-shadow: 0px 3px 6px 0px rgba(0,0,0,0.16);
    overflow: hidden;
    background-color: #FFF;
  }
  .collapse{
    width: 96%;
    margin: 0 auto;
    border-radius: 6px;
    box-shadow: 0px 3px 6px 0px rgba(0,0,0,0.16);
    overflow: hidden;
    margin-bottom: 15px;
  }
  /deep/.van-radio--horizontal{
    margin-left: 20px;
    margin-right: 0;
  }
  .file-box{
    padding: 2% 5% 0;
  }
  .submitButton{
    width: 80%;
    margin: 0 auto;
    border-radius: 14px;
  }
  .timeTit{
    text-align: center;
    font-size: 16px;
    line-height: 27px;
  }
  .action-box{
    padding: 15px 0!important;
    margin-top: 0.4rem;
  }
  .check-box{
    margin-top: 0.4rem;
  }
  .addFamily{
    position: absolute;
    top: -2px;
    right: 0;
    border-radius: 50%;
    display: inline-block;
    width: 0.7rem;
    height: 0.7rem;
  }
  .deleteFamily{
    position: absolute;
    top: -0.35rem;
    right: 6%;
    z-index: 9;
    border-radius: 50%;
    display: inline-block;
    width: 0.7rem;
    height: 0.7rem;
  }
  .familyList{
    margin-top: 0.4rem;
    position: relative;
  }
  .noModify{
    .topTit{
      background-color:#ABABAB ;
      box-shadow: 0px 3px 6px 0px rgba(171,171,171,0.40);
    }
    .van-cell__title{
      color: #B4B0B0;
    }
  }
  .flow_main_box{
    width: 96%;
    margin: 0 auto;
    border-radius: 6px;
    box-shadow: 0px 3px 6px 0px rgba(0,0,0,0.16);
    overflow: hidden;
    background-color: #FFF;
    margin-top: 2%;
    padding: 5% 1%;
    .van-col{
      text-align: center;
    }
    .tit{
      background: #1d6fe9;
      border-radius: 12px;
      font-size: 0.4rem;
      font-family: Source Han Sans CN, Source Han Sans CN-Regular;
      font-weight: 400;
      color: #ffffff;
      line-height: 0.65rem;
      letter-spacing: 0px;
      width: 70%;
      margin: 0 auto;
    }
    .van-step--vertical{
      padding-right: 0;
      text-align: left;
    }
    .van-step--vertical:not(:last-child)::after{
      border: none;
    }
    .van-step--finish{
      color: #1d6fe9;
    }
  }
  .van-goods-action {
    justify-content: center;
  }
  .van-goods-action-button--first {
    border-radius: 0.053333rem;
  }
  .van-goods-action-button--last {
    border-radius: 0.053333rem;
  }
  .van-goods-action-button {
    margin-left: 0.1rem;
  }
</style>
