import React, { Component } from "react";
import Taro, { getCurrentInstance } from "@tarojs/taro";
import { Text, View, Picker } from "@tarojs/components";
import ImagePicker from "../../components/common/imagePicker";
import InquiryModal from "../../components/common/inquiryModal";
import {
  getPridDetail,
  getAccountList,
  selectList,
  AccountExamine,
} from "../../utils/servers/servers";
import {
  getAccountName,
  getTypeName,
  getVehicleName,
  commonAdd,
} from "../../utils/tools";
import { AtTextarea, AtButton } from "taro-ui";
import { resourceAddress } from "../../utils/config";
import "taro-ui/dist/style/components/form.scss";
import "taro-ui/dist/style/components/button.scss";
import "taro-ui/dist/style/components/loading.scss";
import "taro-ui/dist/style/components/icon.scss";
import "taro-ui/dist/style/components/icon.scss";
import "taro-ui/dist/style/components/textarea.scss";
import "taro-ui/dist/style/components/input.scss";

import "../drafts/index.less";

class Drafts extends Component {
  $instance = getCurrentInstance();

  constructor(props) {
    super(props);
    this.state = {
      data: {},
      list: [],
      total: 0,
      bankData: {},
      reason: "",
    };
  }

  componentDidMount() {
    this.$instance.router.params && this.$instance.router.params.id &&
      (
        this.getDetail(),
        this.getAccountList()
      )
  }

  // 报销账户列表
  getMyList(id) {
    let data = {
      pageNo: 1,
      pageSize: 99,
    }
    selectList(data).then(v => {
      if (v.error.length === 0) {
        let list = v.data.list || []
        for (var i = 0; i < list.length; i++) {
          if (list[i].aid == id) {
            this.setState({
              bankData: list[i]
            })
          }
        }
      } else {
        Taro.showToast({ title: v.error[0].message, icon: 'none' })
      }
    }).catch(() => {
      Taro.showToast({
        title: '系统错误,请稍后再试',
        icon: 'none'
      })
    })
  }

  // 报销单详情
  getDetail() {
    getPridDetail({
      id: this.$instance.router.params.id,
    }).then(v => {
      if (v.error.length === 0) {
        let list = [];
        for (let i of (v.data.attachmentUrl || '').split(',')) {
          if (i) {
            list.push({ 'url': resourceAddress + i })
          }
        }
        this.setState({
          data: v.data,
          rangeStartMinuteVal: v.data.releaseStartStr,
          rangeEndMinuteVal: v.data.releaseEndStr,
          totalDuration: v.data.duration,
          attachmentUrl: list,
        })
        // v.data.aid && this.getMyList(v.data.aid)
      } else {
        Taro.showToast({ title: v.error[0].message, icon: 'none' })
      }
    }).catch(() => {
      Taro.showToast({
        title: '系统错误,请稍后再试',
        icon: 'none'
      })
    })
  }

  // 报销详情金额列表
  getAccountList() {
    getAccountList({
      eaid: this.$instance.router.params.id,
    }).then(v => {
      if (v.error.length === 0) {
        let sum = 0
        for (var i = 0; i < v.data.length; i++) {
          // sum += v.data[i].amount
          sum = commonAdd(sum, v.data[i].amount)
        }
        this.setState({
          list: v.data,
          total: sum,
        })

      } else {
        Taro.showToast({ title: v.error[0].message, icon: 'none' })
      }
    }).catch(() => {
      Taro.showToast({
        title: '系统错误,请稍后再试',
        icon: 'none'
      })
    })
  }

  // 审批
  examine(val) {
    Taro.showLoading({ title: '处理中...' });
    AccountExamine({
      id: this.state.data.id,
      reason: this.state.reason,
      status: val,
    })
      .then((v) => {
        Taro.hideLoading();
        if (v.error.length === 0) {
          Taro.showToast({
            title: "操作成功",
            icon: "none",
          });
          this.getDetail()
        } else {
          Taro.showToast({ title: v.error[0].message, icon: "none" });
        }
      })
      .catch((err) => {
        Taro.showToast({ title: "系统错误,请稍后再试", icon: "none" });
      });
  }


  render() {
    const { data, list, total, bankData, attachmentUrl } = this.state
    return (
      <View className="subform">
        <View className="title">{getAccountName(data.type, data.typeOther)}</View>
        {data.type == 1 &&
          <View className="formItem">
            <View className="formName" style={{ width: "86px" }}>公出企业:</View>
            <View className="formValues">{data.userNames}</View>
          </View>}
        {data.type == 1 &&
          <View className="formItem">
            <View className="formName" style={{ width: "86px" }}>公出地点:</View>
            <View className="formValues">{data.districtName}</View>
          </View>}
        {data.type == 1 &&
          <View className="formItem">
            <View className="formName">公出时间:</View>
            <View className="formValue">
              <View
                className="time"
                onClick={() => {
                  this.setState({
                    isPickerRender: true,
                  });
                }}
              >
                <View className="timeContent">
                  <View style={{ textAlign: "center" }}>{this.state.rangeStartMinuteVal}</View>
                  &nbsp;&nbsp;至&nbsp;&nbsp;
                  <View style={{ textAlign: "center" }}>{this.state.rangeEndMinuteVal}</View>
                </View>
              </View>

            </View>
          </View>}
        {data.type == 1 &&
          <View className="formItem">
            <View className="formName">公出时长:</View>
            <View className="formValue">{this.state.totalDuration}小时</View>
          </View>}
        <View className="formItem">
          <View className="formName">申请类型:</View>
          <View className="formValue">{getAccountName(data.type, data.typeOther)}</View>
        </View>
        {data.type != 4 && data.type != 5 &&
          <View className="formItem">
            <View className="formName">报销至订单:</View>
            <View className="formValue">
              <View>
                <View>{data.buyerName}</View>
                <View>{data.contractNo}</View>
              </View>
            </View>
          </View>}
        <View className="formTitle">
          {(data.type == 4 || data.type == 5) ? "申请详细" : "报销详细"}
        </View>
        <View className="formItem">
          <View className="formName">申请人:</View>
          <View className="formValue">{data.aname}</View>
        </View>
        {
          data.type != 4 && data.type != 5 &&
          <View className="formItem">
            <View className="formName">报销公司:</View>
            <View className="formValue">{data.appDepName}</View>
          </View>
        }
        <View className="formItem">
          <View className="formName">
            {data.type == 4
              ? "预借支公司:" : data.type == 5
                ? "抵扣公司:" : "支付公司:"}
          </View>
          <View className="formValue">{data.payDepName}</View>
        </View>
        <View className="formItem">
          <View className="formName">{(data.type == 4 || data.type == 5) ? "说明:" : "报销事由:"}</View>
          <View className="formValue">{data.remarks}</View>
        </View>
        <View className="formTitle">
          {data.type != 4 && data.type != 5 && "报销"}费用详细
        </View>
        {/* 差旅费显示 */}
        {data.type == 1 &&
          list?.map(item =>
            item.type == 1
              ? <View className="unItem" key={item.id}>
                <View className="formItem">
                  <View className="formName">交通工具:</View>
                  <View className="formValue">{getVehicleName(item.vehicle, item.vehicleOther)}</View>
                </View>
                <View className="formItem">
                  <View className="formName">时间:</View>
                  <View className="formValue">
                    <View className="ftxt">{item.startTimeStr}</View>
                    &nbsp;&nbsp;至&nbsp;&nbsp;
                    <View className="ftxt">{item.endTimeStr}</View>
                  </View>
                </View>
                <View className="formItem">
                  <View className="formName">地点:</View>
                  <View className="formValue">
                    <View className="ftxt">{item.startDistrict}</View>
                    &nbsp;&nbsp;至&nbsp;&nbsp;
                    <View className="ftxt">{item.endDistrict}</View>
                  </View>
                </View>
                <View className="formItem">
                  <View className="formName">金额（元）:</View>
                  <View className="formValue">{item.amount}（元）</View>
                </View>
              </View>
              : <View className="formItem" key={item.id}>
                <View className="formName" style={{ width: "86px" }}>{getTypeName(item.type) + ":"}</View>
                <View className="formValues">{item.amount}（元）</View>
              </View>
          )
        }
        {/* 通用 */}
        {(data.type == 0 || data.type == 2 || data.type == 4 || data.type == 5) &&
          list?.map(item =>
            <View className="unItem" key={item.id}>
              <View className="formItem">
                <View className="formName">{data.type == 5 ? "支付时间:" : "需付款时间:"}</View>
                <View className="formValue">{item.agreeTimeStr.slice(0, 10)}</View>
              </View>
              <View className="formItem">
                <View className="formName">
                  {data.type == 4
                    ? "预借支金额:" : data.type == 5
                      ? "抵扣金额:" : "金额:"}
                </View>
                <View className="formValue">{item.amount}（元）</View>
              </View>
            </View>
          )
        }
        {/* 第三方付款 */}
        {data.type == 3 &&
          list?.map(item =>
            <View className="unItem" key={item.id}>
              <View className="formItem">
                <View className="formName">需付款时间:</View>
                <View className="formValue">{item.agreeTimeStr.slice(0, 10)}</View>
              </View>
              <View className="formItem">
                <View className="formName">付款方式:</View>
                <View className="formValue">{["公对公转账"][item.payType]}</View>
              </View>
              <View className="formItem">
                <View className="formName">发票类型:</View>
                <View className="formValue">{["普票", "专票"][item.invoiceType]}</View>
              </View>
              <View className="formItem">
                <View className="formName">发票号:</View>
                <View className="formValue">{item.invoiceNo}</View>
              </View>
              <View className="formItem">
                <View className="formName">付款单位:</View>
                <View className="formValue">{item.payerName}</View>
              </View>
              <View className="formItem">
                <View className="formName">开户银行:</View>
                <View className="formValue">{item.openBank}</View>
              </View>
              <View className="formItem">
                <View className="formName">银行账户:</View>
                <View className="formValue">{item.bankAccounts}</View>
              </View>
              <View className="formItem">
                <View className="formName">开户行地址:</View>
                <View className="formValue">{item.openBankAddress}</View>
              </View>
              <View className="formItem">
                <View className="formName">金额（元）:</View>
                <View className="formValue">{item.amount}</View>
              </View>
            </View>
          )
        }
        {
          data.type != 4 && data.debitTotalAmount &&
          <View className="formItem">
            <View className="formName">预借支:</View>
            <View className="formValue"><Text style={{ color: "red" }}>{data.debitTotalAmount}</Text>（元）</View>
          </View>
        }
        {
          data.type != 4 && data.type != 5 &&
          <View className="formItem">
            <View className="formName">总金额:</View>
            <View className="formValue"><Text style={{ color: "red" }}>{total}</Text>（元）</View>
          </View>
        }
        {
          data.type != 4 && data.type != 5 &&
          <View className="formItem">
            <View className="formName">实报金额:</View>
            <View className="formValue"><Text style={{ color: "red" }}>
              {(total > data.debitTotalAmount) ? commonAdd(total, -data.debitTotalAmount) : 0}
            </Text>（元）</View>
          </View>
        }
        <View className="formItem" style={{ display: "block", paddingBottom: 0 }}>
          <View className="formName">附件:</View>
          <View
            className="formValue"
            style={{ paddingTop: "10px", textAlign: "left" }}
          >
            {attachmentUrl && attachmentUrl.length > 0 &&
              <ImagePicker
                files={attachmentUrl || []}
                showAddBtn={false}
              />}
          </View>
        </View>
        {data.type != 3 && data.type != 5 &&
          <View className="formTitle" style={{ marginTop: "20px" }}>
            报销至收款账户
          </View>}
        {data.type != 3 && data.type != 5 &&
          <View className="unobstructedList">
            {<View className="unItem" >
              <View className="formItem">
                <View className="formName">收款人：{data.name}</View>
              </View>
              <View className="formItem">
                <View className="formName">收款银行：{data.bank}</View>
              </View>
              <View className="formItem">
                <View className="formName">收款账户：{data.accounts}</View>
              </View>
            </View>}
          </View>}

        {
          data.examine == 1 &&
          <View>
            <View className="formTitle" style={{ marginTop: "20px" }}>
              填写审批意见
            </View>
            <AtTextarea
              value={this.state.reason}
              onChange={(value) => {
                this.setState({
                  reason: value,
                });
              }}
              maxLength={30}
              placeholder="请填写审批意见"
            />
            <View className="operation">
              <AtButton
                type="secondary"
                circle
                loading={this.state.loading}
                onClick={() => {
                  if (!this.state.reason) {
                    Taro.showToast({ title: "请先填写审批意见", icon: "none" });
                    return;
                  }
                  this.setState({
                    isInquiryOpened: true,
                    inquiryTitle: "提醒",
                    inquiryContent: "您确定要驳回此申请吗?",
                    inquiryFn: () => {
                      this.examine(3);
                    },
                  });
                }}
              >
                驳回
              </AtButton>
              <AtButton
                type="primary"
                loading={this.state.loading}
                circle
                onClick={() => {
                  if (!this.state.reason) {
                    Taro.showToast({ title: "请先填写审批意见", icon: "none" });
                    return;
                  }
                  this.setState({
                    isInquiryOpened: true,
                    inquiryTitle: "提醒",
                    inquiryContent: "您确定要同意此申请吗?",
                    inquiryFn: () => {
                      this.examine(1);
                    },
                  });
                }}
              >
                同意
              </AtButton>
            </View>
          </View>
        }

        {/* 二级确认弹窗 */}
        <InquiryModal
          isOpened={this.state.isInquiryOpened}
          title={this.state.inquiryTitle}
          content={this.state.inquiryContent}
          onClose={() => {
            this.setState({
              isInquiryOpened: false,
              inquiryTitle: "",
              inquiryContent: "",
              isNo: true,
            });
          }}
          onDetermine={() => {
            this.state.inquiryFn();
            this.setState({
              isInquiryOpened: false,
              inquiryTitle: "",
              inquiryContent: "",
              isNo: true,
              inquiryFn: () => { },
            });
          }}
        />

      </View>
    );
  }
}

export default Drafts;
