import React, { Component } from "react";
import Taro, { getCurrentInstance } from "@tarojs/taro";
import { Text, View, Picker, Button, Image } from "@tarojs/components";
import ImagePicker from "../../components/common/imagePicker";
import InquiryModal from "../../components/common/inquiryModal";
import AuditModal from "../../components/common/auditModal";
import AccountModal from "../../components/common/accountModal";
import {
  getPridDetail,
  getAccountList,
  selectList,
  AccountExamine,
  getMainExpenseDetail,
  getDepartmentList,
  subMainAccount,
} from "../../utils/servers/servers";
import {
  getAccountName,
  getSecondaryAccountName,
  getTypeName,
  getVehicleName,
  commonAdd,
  copyText,
  getNewOptions,
  removeNull,
} from "../../utils/tools";
import {
  AtTextarea,
  AtButton,
  AtIcon,
  AtModal,
  AtModalHeader,
  AtModalContent,
  AtRadio,
  AtModalAction,
} from "taro-ui";
import { resourceAddress } from "../../utils/config";
import Reviewed from '../../image/reviewed.png'
import Rejected from '../../image/rejected.png'
import Passed from '../../image/passed.png'

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/textarea.scss";
import "taro-ui/dist/style/components/input.scss";

import "./index.less";

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

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

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

  componentDidShow() {
    let pages = Taro.getCurrentPages();
    let currPage = pages[pages.length - 1]; // 获取当前页面
    const { data } = this.state
    const obj = {
      buyerName: currPage.data.name || data.buyerName,
      orderNo: currPage.data.orderNo || data.orderNo,
      contractNo: currPage.data.contractNo || data.contractNo,
    }
    this.setState({
      data: { ...this.state.data, ...obj },
    })
  }

  // 部门数据
  getDepartmentList() {
    getDepartmentList({}).then(v => {
      let thedata = v.data;
      let theArr = [];
      if (!thedata) {
        if (v.error && v.error.length) {
          Taro.showToast({ title: v.error[0].message, icon: 'none' })
        }
      } else {
        thedata.map(function (item, index) {
          theArr.push({
            key: index,
            name: item.name,
            id: item.id
          });
        });
      }
      this.setState({
        departmentArr: theArr
      });
    }).catch(() => {
      Taro.showToast({
        title: '系统错误,请稍后再试',
        icon: 'none'
      })
    })
  }

  // 报销账户列表
  getMyList(sta) {
    let data1 = { status: 1 }
    let data2 = {
      pageNo: 1,
      pageSize: 99,
    }
    selectList(sta ? data2 : data1).then(v => {
      if (v.error.length === 0) {
        let list = v.data.list || []
        if (list?.length > 0) {
          if (sta) {
            this.setState({
              accountsList: list
            })
          } else {
            let obj = {
              name: list[0].name,
              bank: list[0].bank,
              accounts: list[0].accounts,
              eaaid: list[0].id,
            }
            this.setState({
              data: { ...this.state.data, ...obj },
            })
          }
        }
      } else {
        Taro.showToast({ title: v.error[0].message, icon: 'none' })
      }
    }).catch(() => {
      Taro.showToast({
        title: '系统错误,请稍后再试',
        icon: 'none'
      })
    })
  }

  // 详情
  getDetail() {
    getMainExpenseDetail({
      id: this.$instance.router.params.id,
    }).then(v => {
      if (v.error.length === 0) {
        this.setState({
          data: v.data,
        })
        v.data.status == 0 && this.getMyList()
      } else {
        Taro.showToast({ title: v.error[0].message, icon: 'none' })
      }
    }).catch(() => {
      Taro.showToast({
        title: '系统错误,请稍后再试',
        icon: 'none'
      })
    })
  }

  getUrls(url) {
    let list = [];
    for (let i of (url || '').split(',')) {
      if (i) {
        list.push({ 'url': resourceAddress + i })
      }
    }
    return list
  }

  // 报销详情金额列表
  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",
          });
          Taro.navigateBack({
            delta: 1
          })
          // this.getDetail()
        } else {
          Taro.showToast({ title: v.error[0].message, icon: "none" });
        }
      })
      .catch((err) => {
        Taro.showToast({ title: "系统错误,请稍后再试", icon: "none" });
      });
  }

  onSubmit(val) {
    this.setState({
      loading: true,
    });
    const { data } = this.state
    let comData = {
      id: data.id,
      orderNo: data.orderNo,
      applyDep: data.applyDep,
      payDep: data.payDep,
      eaaid: data.eaaid,
      remarks: data.remarks,
      status: val
    }
    let comData1 = {
      id: data.id,
      status: val
    }
    subMainAccount(removeNull(val == 4 ? comData1 : comData))
      .then((v) => {
        this.setState({
          loading: false,
        })
        if (v.error.length === 0) {
          Taro.showToast({
            title: "操作成功！",
            icon: "none",
          });
          // Taro.switchTab({
          //   url: "/pages/recordlist/index",
          // });
          Taro.navigateBack({
            delta: 1
          })
        } else {
          Taro.showToast({
            title: v.error[0].message,
            icon: "none",
          });
        }
      })
      .catch(() => {
        this.setState({
          loading: false,
        });
      });
  }

  // 取消添加
  onAccountClose() {
    this.setState({
      accountvisible: "",
    })
  }

  // 添加收款账户
  onAccountOk() {
    this.setState({
      accountvisible: "",
    }, () => { this.getMyList() })
  }

  // 确认收款账户
  selectOn() {
    let list = this.state.accountsList
    for (var i = 0; i < list.length; i++) {
      if (list[i].id == this.state.aid) {
        const obj = {
          eaaid: list[i].id,
          name: list[i].name,
          bank: list[i].bank,
          accounts: list[i].accounts,
        }
        this.setState({
          upaccount: false,
          data: { ...this.state.data, ...obj },
        })
      }
    }
  }

  render() {
    const { data, } = this.state
    const departmentArr = this.state.departmentArr || [];
    const isEdit = data.status == 0 && data.processStatus == 0
    return (
      <View className="subform">
        {/* <View className="title">
          {getAccountName(data.type, data.typeOther)}
        </View> */}
        {<View className="formItem">
          <View className="formName">报销编号：</View>
          <View className="formValue">{data.checkNo}</View>
          <View className='tbt'
            onClick={e => { e.stopPropagation(); copyText(data.checkNo) }}
          >复制编号</View>
        </View>}
        {/* <View className="formItem">
          <View className="formName" >总金额：</View>
          <View className="formValue">{data.totalAmount}元</View>
        </View> */}
        <View className="formItem">
          <View className="formName">报销至订单：</View>
          <View className="formValue"
            onClick={() => {
              isEdit &&
                Taro.navigateTo({
                  url: "/pages/dataindex/index"
                })
            }}>
            <View>
              <View>{data.contractNo}</View>
            </View>
            {isEdit && <AtIcon value="chevron-right" size="20" color="#000000" />}
          </View>
        </View>
        <View className="formItem">
          <View className="formName">报销时间：</View>
          <View className="formValue">{data.createTimeStr}</View>
        </View>
        <View className="formTitle">
          {"报销详细"}
          <Image className="ficon"
            src={data.status == 1
              ? Reviewed : data.status == 2
                ? Passed : data.status == 3 && Rejected}
          />
        </View>
        <View className="formItem">
          <View className="formName">申请人：</View>
          <View className="formValue">{data.aname}</View>
        </View>
        <View className="formItem">
          <View className="formName">报销公司：</View>
          {isEdit ?
            <View className="formValue">
              <Picker
                value={departmentArr.findIndex(item => item.id === data.applyDep)}
                range={departmentArr} rangeKey='name' mode='selector'
                onChange={(e) => {
                  const obj = { applyDep: departmentArr[e.detail.value].id, applyDepName: departmentArr[e.detail.value].name }
                  this.setState({
                    data: { ...data, ...obj },
                  })
                }}>
                <View>
                  {data.applyDepName}
                  <AtIcon value="chevron-right" size="20" color="#000000" />
                </View>
              </Picker>
            </View> :
            <View className="formValue">{data.applyDepName}</View>}
        </View>
        <View className="formItem">
          <View className="formName">支付公司：</View>
          {isEdit ?
            <View className="formValue">
              <Picker
                value={departmentArr.findIndex(item => item.id === data.payDep)}
                range={departmentArr} rangeKey='name' mode='selector'
                onChange={(e) => {
                  const obj = { payDep: departmentArr[e.detail.value].id, payDepName: departmentArr[e.detail.value].name }
                  this.setState({
                    data: { ...data, ...obj },
                  })
                }}>
                <View>
                  {data.payDepName}
                  <AtIcon value="chevron-right" size="20" color="#000000" />
                </View>
              </Picker>
            </View> :
            <View className="formValue">{data.payDepName}</View>}
        </View>
        <View className="formItem">
          <View className="formName">
            报销事由：
          </View>
          {isEdit ?
            <View className="formValues">
              <AtTextarea
                value={data.remarks == null ? "" : data.remarks}
                onChange={e => {
                  const obj = { remarks: e }
                  this.setState({
                    data: { ...data, ...obj }
                  })
                }}
                height={75}
                maxLength={50}
                placeholder={(data.type == 4 || data.type == 5) ? "请填写说明：" : "请填写报销事由"}
              />
            </View> :
            <View className="formValueremarks">{data.remarks}</View>}
        </View>
        <View className="formTitle">
          报销费用详细
        </View>
        {
          data.sonList?.map((it) =>
            <View key={it.id} style={{ borderTop: "1px solid #eae8e8" }}>
              <View className="formItem" style={{ fontWeight: "bold" }}>
                <View className="formName">报销金额：</View>
                <View className="formValue">{it.amount}（元）</View>
              </View>
              <View className="formItem" style={{ fontWeight: "bold" }}>
                <View className="formName">报销类型：</View>
                <View className="formValue">
                  {getAccountName(it.type, it.typeOther)}
                  {it.type == 2 && (" - " + getSecondaryAccountName(it.secondaryType, it.secondaryTypeOther))}
                </View>
              </View>
              {it.type == 1 &&
                <View className="formItem">
                  <View className="formName">公出企业：</View>
                  <View className="formValue">{it.userNames}</View>
                </View>}
              <View className="formItem">
                <View className="formName">{it.type == 1 ? "公出时间" : "费用时间"}：</View>
                <View className="formValue">
                  {!it.releaseStart ? "" : (it.releaseStart.slice(0, 10) + " 至 " + it.releaseEnd.slice(0, 10))}
                </View>
              </View>
              {/* 差旅费显示 */}
              {it.type == 1 &&
                it.detList?.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)}
                          （{item.startDistrict + " - " + item.endDistrict}）
                          {item.amount}（元）
                        </View>
                      </View>
                    </View>
                    : <View className="unItem" key={item.id}>
                      <View className="formItem" key={item.id}>
                        <View className="formName" >{getTypeName(item.type) + "："}</View>
                        <View className="formValue">{item.amount}（元）</View>
                      </View>
                    </View>
                )
              }
              {/* 通用 */}
              {(it.type == 0 || it.type == 2 || it.type == 4 || it.type == 5) &&
                it.detList?.map(item =>
                  <View className="unItem" key={item.id}>
                    {!!item.agreeTimeStr &&
                      <View className="formItem">
                        <View className="formName">{it.type == 5 ? "支付时间：" : "需付款时间："}</View>
                        <View className="formValue">{item.agreeTimeStr.slice(0, 10)}</View>
                      </View>}
                    <View className="formItem">
                      <View className="formName">
                        {it.type == 4
                          ? "预借支金额：" : it.type == 5
                            ? "抵扣金额：" : "金额："}
                      </View>
                      <View className="formValue">{item.amount}（元）</View>
                    </View>
                  </View>
                )
              }
              {/* 第三方付款 */}
              {it.type == 3 &&
                it.detList?.map(item =>
                  <View className="unItem" key={item.id}>
                    {!!item.agreeTimeStr &&
                      <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>
                )
              }
              {
                it.settlementAmount != 0 && it.type != 4 && it.type != 5 &&
                <View className="formItem">
                  <View className="formName">抵扣金额：</View>
                  <View className="formValue">{it.settlementAmount}（元）</View>
                </View>
              }
              <View className="formItem" style={{ display: "block", paddingBottom: 0 }}>
                <View className="formName">附件：</View>
                <View
                  className="formValue"
                  style={{ paddingTop: "10px", textAlign: "left" }}
                >
                  {this.getUrls(it.attachmentUrl) && this.getUrls(it.attachmentUrl).length > 0 &&
                    <ImagePicker
                      files={this.getUrls(it.attachmentUrl)}
                      showAddBtn={false}
                    />}
                </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" }}>{data.totalAmount}</Text>（元）</View>
          </View>
        } */}
        {
          data.type != 4 && data.type != 5 &&
          <View className="formItem" style={{ fontWeight: "bold" }}>
            <View className="formName">本次报销金额：</View>
            <View className="formValue"><Text style={{ color: "red" }}>{data.amount}</Text>（元）</View>
          </View>
        }
        <View className="formTitle" style={{ marginTop: "20px" }}>
          报销账户
        </View>
        <View className="unobstructedList" style={{ marginBottom: "20px" }}>
          {
            !data.eaaid && isEdit ?
              <View className="noAccout"
                onClick={() => { this.setState({ accountvisible: true }) }}>
                暂未有收款账户
                <View className="nbt">去添加 &gt;</View>
              </View> :
              <View className="unItem" >
                {isEdit &&
                  <View className="edit"
                    onClick={() => {
                      this.setState({
                        upaccount: true,
                        // aid: bankData.id,
                      }, () => {
                        this.getMyList(true)
                      })
                    }}
                  >修改</View>}
                <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.status != 0 &&
          <View
            className="select"
            onClick={(e) => {
              e.stopPropagation();
              this.setState({
                visible: true,
                id: data.id
              });
            }}
          >
            查看审核详情
            <AtIcon value="chevron-right" size="20" color="#fff" />
          </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>
        }
        {
          isEdit &&
          <View className="bottom">
            <AtButton
              disabled={this.state.loading}
              type="primary"
              circle
              onClick={() => {
                this.onSubmit(1)
              }}
            >
              提交报销订单
            </AtButton>
          </View>
        }
        {
          data.examine == 2 && data.status == 3 &&
          <View className="bottom">
            <AtButton
              className="bt"
              disabled={this.state.loading}
              type="primary"
              circle
              onClick={() => {
                this.setState({
                  isInquiryOpened: true,
                  inquiryTitle: "提醒",
                  inquiryContent: "您确定取消该报销订单吗?",
                  inquiryFn: () => {
                    this.onSubmit(4);
                  },
                });
              }}
            >
              取消报销订单
            </AtButton>
            <View className="btips">注：取消后，请重新发起报销</View>
          </View>
        }
        {/* 收款账户添加 */}
        {
          this.state.accountvisible != "" &&
          <AccountModal
            isDefault={true}
            isSub={true}
            visible={this.state.accountvisible}
            onClose={this.onAccountClose.bind(this)}
            onOk={this.onAccountOk.bind(this)}
          />
        }
        {/* 收款账户列表 */}
        <AtModal isOpened={this.state.upaccount}>
          <AtModalHeader>请选择收款账户</AtModalHeader>
          <AtModalContent>
            <AtRadio
              options={getNewOptions(this.state.accountsList)}
              value={this.state.aid}
              onClick={e => { this.setState({ aid: e }) }}
            />
          </AtModalContent>
          <AtModalAction>
            <Button type='secondary' onClick={() => { this.setState({ upaccount: false, accountsList: [] }) }}>取消</Button>
            <Button type='primary' onClick={() => { this.selectOn() }}>确定</Button>
          </AtModalAction>
        </AtModal>
        {/* 二级确认弹窗 */}
        <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: () => { },
            });
          }}
        />
        {/* 审核详情 */}
        {this.state.visible &&
          <AuditModal
            id={this.state.id}
            isOpened={this.state.visible}
            onClose={() => {
              this.setState({
                visible: false
              })
            }}
          />}

      </View>
    );
  }
}

export default Drafts;
