<template>
  <view class="quickCreateOrder">
    <view class="qco_msg" v-html="dataObj.msg"></view>
    <!-- 起点科室,终点科室 -->
    <block v-if="qucikCreateOrderType === 'other' && (dataObj.start || dataObj.end)">
      <!-- 返回值的departmentStrategy是201 则是默认发起科室 -->
      <!-- 返回值的departmentStrategy是202 则是固定科室范围 -->
      <!-- 返回值的departmentStrategy是203 则是固定科室 -->
      <!-- 返回值的departmentStrategy是204 则是自主填写 -->
      <!-- 返回值的departmentStrategy是205 则是固定科室类型 -->
      <!-- 100013 （护士端一键建单展示策略）取起点科室，和msg值展示 -->
      <!-- <block v-if="dataObj.status == 100013"> -->
      <view class="select_block" @click="selectDept('start')">
        <!-- 默认科室和固定科室 -->
        <text class="select_label"
          :class="{disableColor:dataObj.start.start.departmentStrategy == 201 || dataObj.start.start.departmentStrategy == 203}">起点科室</text>
        <view class="select_placeholder"
          v-if="dataObj.start.start.departmentStrategy == 201 || dataObj.start.start.departmentStrategy == 203">
          {{deptDisplay == 1? startDept.dept: startDept.deptalias}}
        </view>
        <!-- 固定科室范围,固定科室类型，自主选择 -->
        <view class="select_placeholder" v-else>
          <text>{{startDept.id?(deptDisplay == 1? startDept.dept: startDept.deptalias):'请选择起点科室'}}</text>
          <text class="pda pda-xiangyou"></text>
        </view>
      </view>
      <view class="select_block" @click="selectDept('end')">
        <!-- 默认科室和固定科室 -->
        <text class="select_label"
          :class="{disableColor:dataObj.end.end.departmentStrategy == 201 || dataObj.end.end.departmentStrategy == 203}">终点科室</text>
        <view class="select_placeholder"
          v-if="dataObj.end.end.departmentStrategy == 201 || dataObj.end.end.departmentStrategy == 203">
          {{deptDisplay == 1? endDept.dept: endDept.deptalias}}
        </view>
        <!-- 固定科室范围,固定科室类型，自主选择 -->
        <view class="select_placeholder" v-else>
          <text>{{endDept.id?(deptDisplay == 1? endDept.dept: endDept.deptalias):'请选择终点科室'}}</text>
          <text class="pda pda-xiangyou"></text>
        </view>
      </view>
      <!-- </block> -->
    </block>
    <!-- 备注 -->
    <view class="remarks" v-if="dataObj.remarksSwitch == 1">
      <textarea :focus="remarksFocus" class="remarks_textarea" auto-height :maxlength="100"
        placeholder-style="color:#999" :placeholder="
          dataObj.remarksPrompts || '请填写工单备注,不超过100个字符'
        " v-model="workOrderRemark" />
    </view>
    <!-- 快捷输入,历史输入 -->
    <view class="quickAndHistory" v-if="dataObj.remarksSwitch == 1 && dataObj.customRemarks.length">
      <view class="quickAndHistory_header"> 快捷输入 </view>
      <view class="quickAndHistory_container">
        <view class="quickAndHistory_item" @click="addRemarks(customRemark)"
          v-for="(customRemark, i) in dataObj.customRemarks" :key="i">
          {{ customRemark }}
        </view>
      </view>
    </view>
    <view class="quickAndHistory" v-if="dataObj.remarksSwitch == 1 && historyCustomRemarks.length">
      <view class="quickAndHistory_header"> 历史输入 </view>
      <view class="quickAndHistory_container">
        <view class="quickAndHistory_item" @click="addRemarks(historyCustomRemark)"
          v-for="(historyCustomRemark, i) in historyCustomRemarks" :key="i">
          {{ historyCustomRemark }}
        </view>
      </view>
    </view>
    <!-- 底部 -->
    <seiminFooterBtn :btns="btns"></seiminFooterBtn>
    <seiminModel ref="seiminModel"></seiminModel>
    <seiminPicker ref="sPicker" :title="pickerTitle" titleColor="#808080" titleFontSize="28rpx" confirmColor="#333"
      confirmFontSize="38rpx" confirmFontWeight="500" itemFontSize="28rpx" @onClose="closePicker"
      @onConfirm="confirmPicker" :pickerList="deptList">
    </seiminPicker>
  </view>
</template>

<script>
  import {
    mapState,
    mapMutations
  } from "vuex";
  import {
    reqBuildTrip,
    reqRecentRemarks,
    reqBuildOrder,
  } from "../../request/api.js";
  import {
    SOURCEID
  } from "../../utils/enum.sourceid.js";
  export default {
    data() {
      return {
        // 传递过来的参数
        queryParams: {},
        // 选择的起点科室
        startDept: {},
        // 选择的终点科室
        endDept: {},
        // 固定科室范围的科室列表
        deptList: [],
        //选择起点科室（start）或终点科室（end）
        selectdDeptType: '',
        //选择院区picker的title
        pickerTitle: '',
        // 工单备注是否获取焦点
        remarksFocus: true,
        // 工单备注
        workOrderRemark: "",
        // 获取到的数据集合对象(历史输入除外)
        dataObj: {},
        // 历史输入
        historyCustomRemarks: [],
        //底部按钮
        btns: [{
            name: "回到首页",
            type: "default",
            click: () => {
              uni.navigateTo({
                url: "/pages/index/index",
              });
            },
          },
          {
            name: "确认",
            type: "primary",
            click: () => {
              this.submitData();
            },
          },
        ],
      };
    },
    computed: {
      ...mapState('user', ['loginInfo']),
      ...mapState([
        "qucikCreateOrderType",
        "qucikCreateOrderTypeId",
        "deptDisplay",
        'searchDeptParams',
        'searchDeptResultList'
      ]),
    },
    methods: {
      ...mapMutations(['changeSearchDeptParams', 'changeSearchDeptResultList']),
      // 添加备注
      addRemarks(customRemark) {
        this.remarksFocus = false;
        this.$nextTick(() => {
          this.remarksFocus = true;
        });
        this.workOrderRemark += customRemark;
      },
      //获取所有数据
      getData(qucikCreateOrderType, qucikCreateOrderTypeId) {
        uni.showLoading({
          title: "加载中",
        });
        let postData1 = {};
        let postData2 = {
          taskTypeId: qucikCreateOrderTypeId,
          deptId: this.loginInfo.user.dept.id,
        };
        if (qucikCreateOrderType === "specimen") {
          //标本快捷建单
          postData1 = {
            taskTypeId: qucikCreateOrderTypeId,
            deptId: this.loginInfo.user.dept.id,
          };
        } else if (qucikCreateOrderType === "other") {
          //其他临床服务快捷建单
          postData1 = {
            taskTypeId: qucikCreateOrderTypeId,
          };
        }
        Promise.all([reqBuildTrip(postData1), reqRecentRemarks(postData2)]).then(
          (values) => {
            uni.hideLoading();
            this.getBuildTrip(values[0]);
            this.getRecentRemarks(values[1]);
          }
        );
      },
      // 获取数据(除历史输入)
      getBuildTrip(res) {
        if (
          res.status == 200 ||
          res.status == 100012 ||
          res.status == 100013 ||
          res.status == 100014 ||
          res.status == 100015
        ) {
          // 处理返回的数据
          if (res.customRemarks) {
            res.customRemarks = res.customRemarks.split("$");
          } else {
            res.customRemarks = [];
          }
          // 处理msg
          if (res.msg.includes("<b>")) {
            res.msg = res.msg.replace(/<b>/g, '<text class="green">');
            res.msg = res.msg.replace(/<\/b>/g, "</text>");
          }
          if (res.start || res.end) {
            //其他服务建单
            if (
              res.start.start.departmentStrategy == 201 ||
              res.start.start.departmentStrategy == 203) {
              this.startDept = res.start.start.list[0];
            }
            if (
              res.end.end.departmentStrategy == 201 ||
              res.end.end.departmentStrategy == 203) {
              this.endDept = res.end.end.list[0];
            }

            if (
              res.start.start.departmentStrategy == 204 ||
              res.start.start.departmentStrategy == 205 ||
              res.end.end.departmentStrategy == 204 ||
              res.end.end.departmentStrategy == 205
            ) {
              if (this.queryParams.isShow) {
                this.startDept = this.searchDeptResultList.start || {};
                this.endDept = this.searchDeptResultList.end || {};
              } else {
                this.changeSearchDeptResultList({});
              }
            }
          }
          this.dataObj = res;
        }
      },
      // 获取历史输入
      getRecentRemarks(res) {
        if (res.state == 200) {
          this.historyCustomRemarks = res.data || [];
        }
      },
      // 提交数据,建单
      submitData() {
        let postData = {};
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        if (this.qucikCreateOrderType === "specimen") {
          //标本建单
          postData = {
            urgent: 0,
            workOrder: {
              sourceId: SOURCEID["护士端"],
              workOrderRemark: this.workOrderRemark,
              taskType: {
                id: this.qucikCreateOrderTypeId,
              },
              createDept: this.loginInfo.user.dept.id,
              startDept: {
                id: this.loginInfo.user.dept.id,
              },
            },
          };
        } else if (this.qucikCreateOrderType === "other") {
          // 其他服务建单
          let startDept = {
            id: this.startDept.id,
          };; //起点科室
          let endDepts = [{
            id: this.endDept.id,
          }]; //终点科室
          // 验证起点科室和终点科室必填
          if (!startDept.id) {
            this.$refs.seiminModel.showChangeDept({
              skin: "toast",
              icon: "error",
              content: "请选择起点科室",
            });
            uni.hideLoading();
            return;
          }
          if (!endDepts[0].id) {
            this.$refs.seiminModel.showChangeDept({
              skin: "toast",
              icon: "error",
              content: "请选择终点科室",
            });
            uni.hideLoading();
            return;
          }
          //请求参数
          postData = {
            workOrder: {
              sourceId: SOURCEID["护士端"],
              workOrderRemark: this.workOrderRemark,
              taskType: {
                id: this.qucikCreateOrderTypeId,
              },
              createDept: this.loginInfo.user.dept.id,
              startDept,
              endDepts,
            },
          };
        }

        reqBuildOrder(postData).then((res) => {
          uni.hideLoading();
          if (res.status == 200) {
            this.$refs.seiminModel.showChangeDept({
              skin: "toast",
              content: "创建成功",
              btns: [{
                name: "知道了",
                textColor: "#49B856",
                flex: 1,
                click() {
                  uni.navigateTo({
                    url: "/pages/index/index",
                  });
                },
              }, ],
            });
          } else {
            this.$refs.seiminModel.showChangeDept({
              skin: "toast",
              icon: "error",
              content: res.msg || "操作失败",
            });
          }
        });
      },
      //关闭
      closePicker() {
        this.$refs.sPicker._close();
      },
      //打开
      openPicker() {
        this.$refs.sPicker._open();
      },
      //确定：接收子组件传来的参数
      confirmPicker(checkedObj) {
        this[this.selectdDeptType + 'Dept'] = {
          id: checkedObj.value,
          dept: checkedObj.label,
          deptalias: checkedObj.labelAlias
        };
      },
      // 选择起点科室
      selectDept(type) {
        this.selectdDeptType = type; //存储类型
        if (
          this.dataObj.start.start.departmentStrategy == 201 ||
          this.dataObj.start.start.departmentStrategy == 203 ||
          this.dataObj.end.end.departmentStrategy == 201 ||
          this.dataObj.end.end.departmentStrategy == 203) {
          //默认科室和固定科室不能选科室
          return;
        }
        if (this.dataObj[type][type].departmentStrategy == 202) {
          // 固定科室范围
          this.pickerTitle = type === 'start' ? '请选择起点科室' : '请选择终点科室';
          this.deptList = this.dataObj[type][type].list.map(v => ({
            value: v.id,
            label: v.dept,
            labelAlias: v.deptalias
          }))
          console.log(this.deptList, this.pickerTitle)
          this.openPicker();
        } else if (this.dataObj[type][type].departmentStrategy == 204 || this.dataObj[type][type].departmentStrategy ==
          205) {
          // 固定科室类型,自主选择
          let params = {
            backUrl: "/pages/quickCreateOrder/quickCreateOrder?isShow=true", //返回的url
            type: `selectDept_${type}_qucikCreateOrder`, //快捷建单选择起点科室
            ids: this.dataObj[type].deptIds || '',
            departmentStrategy: this.dataObj[type][type].departmentStrategy, //固定科室类型,自主选择
          };
          if (this.dataObj[type][type].departmentStrategy == 205) {
            //固定科室类型
            params.deptType = this.dataObj[type][type][type + 'TypeId']; //科室类型
          }
          this.changeSearchDeptParams(params);
          uni.navigateTo({
            url: "/pages/searchDept/searchDept",
          });
        }
      }
    },
    onLoad(queryParams) {
      this.queryParams = queryParams;
      console.log(queryParams);
      console.log(this.qucikCreateOrderType, this.qucikCreateOrderTypeId);
      this.getData(this.qucikCreateOrderType, this.qucikCreateOrderTypeId);
    },
  };
</script>

<style lang="scss" scoped>
  .quickCreateOrder {
    margin-bottom: 100rpx;

    .qco_msg {
      min-height: 144rpx;
      padding: 32rpx 160rpx;
      color: #999;
      line-height: 40rpx;
      font-size: 28rpx;
      text-align: center;
    }

    // 起点科室,终点科室
    .select_block {
      padding: 0 30rpx;
      height: 88rpx;
      font-size: 34rpx;
      border-top: 1px solid #e5e5e5;
      background-color: #fff;
      @include flex(space-between, center);

      .select_label {
        color: #000;

        &.disableColor {
          color: #999;
        }
      }

      .select_placeholder {
        color: #888;
        @include flex(flex-start, center);

        .pda-xiangyou {
          font-size: 24rpx;
          margin-left: 30rpx;
        }
      }
    }

    // 备注
    .remarks {
      min-height: 150rpx;
      background-color: #fff;
      border-top: 1px solid #e5e5e5;
      border-bottom: 1px solid #e5e5e5;
      padding: 22rpx 25rpx;

      .remarks_textarea {
        width: 100%;
        min-height: 100rpx;
      }
    }

    // 快捷输入,历史输入
    .quickAndHistory {
      padding: 43rpx 25rpx 0;

      .quickAndHistory_header {
        font-weight: bold;
        font-size: 34rpx;
        padding-bottom: 24rpx;
        color: #333;
      }

      .quickAndHistory_container {
        @include flex;
        flex-wrap: wrap;

        .quickAndHistory_item {
          height: 66rpx;
          font-size: 28rpx;
          border-radius: 33rpx;
          background-color: #fff;
          line-height: 66rpx;
          padding: 0 24rpx;
          color: #666;
          margin-bottom: 11rpx;
          margin-right: 24rpx;
          @include clamp;
        }
      }
    }
  }
</style>
